<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="true">

<script data-ad-client="ca-pub-3331353808689126" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>







  <meta name="baidu-site-verification" content="true">







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="算法,">





  <link rel="alternate" href="/atom.xml" title="爱吃jelly的Jelly" type="application/atom+xml">






<meta name="description" content="来源《程序员代码面试指南》左程云著">
<meta name="keywords" content="算法">
<meta property="og:type" content="article">
<meta property="og:title" content="高频算法题-zs">
<meta property="og:url" content="https://jelly54.github.io/alg-frequenceCode/index.html">
<meta property="og:site_name" content="爱吃jelly的Jelly">
<meta property="og:description" content="来源《程序员代码面试指南》左程云著">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/11/1oDNut.png">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/16/39kjYj.png">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/16/39kgeO.png">
<meta property="og:updated_time" content="2020-03-07T03:47:15.794Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="高频算法题-zs">
<meta name="twitter:description" content="来源《程序员代码面试指南》左程云著">
<meta name="twitter:image" content="https://s2.ax1x.com/2020/02/11/1oDNut.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://jelly54.github.io/alg-frequenceCode/">






  <meta name="baidu-site-verification" content="t21ZdXzSqf">



<meta name="google-site-verification" content="VmrkZiYJtPrIIH8zlY82aG2_l1Ykrp3JZ3HQbMt0qCo">

  <title>高频算法题-zs | 爱吃jelly的Jelly</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/jelly54" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">爱吃jelly的Jelly</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">就揪啾  就是 Jelly</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于作者
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://jelly54.github.io/alg-frequenceCode/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Big Jelly">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱吃jelly的Jelly">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">高频算法题-zs</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-18T10:53:54+08:00">
                2018-10-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/数据结构与算法/" itemprop="url" rel="index">
                    <span itemprop="name">数据结构与算法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  13.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  69
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>来源《程序员代码面试指南》左程云著</p>
<a id="more"></a>

<h1 id="排序问题"><a href="#排序问题" class="headerlink" title="排序问题"></a>排序问题</h1><h2 id="小和问题"><a href="#小和问题" class="headerlink" title="小和问题"></a>小和问题</h2><p>在一个数组中， 每一个数左边比当前数小的数累加起来， 叫做这个数组的小和。 求一个数组<br>的小和。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">例子：</span><br><span class="line">[1,3,4,2,5]</span><br><span class="line">1左边比1小的数， 没有；</span><br><span class="line">3左边比3小的数， 1；</span><br><span class="line">4左边比4小的数， 1、 3；</span><br><span class="line">2左边比2小的数， 1；</span><br><span class="line">5左边比5小的数， 1、 3、 4、 2；</span><br><span class="line">所以小和为1+1+3+1+1+3+4+2=16</span><br></pre></td></tr></table></figure>

<p><strong>题解：</strong></p>
<p>利用归并排序，在merge的时候计算有几个数比它小。因为分区两边都将是有序的，当左边分组元素小于右边分组元素，将会有  (r - p2 + 1) * arr[p1] 个小数。r为最右边边界，p2为右边分组元素下标，arr[p1] 为左边分组元素，相加则为产生的小和。</p>
<p>因为整体将趋于有序，而且每次merge之后元素都将归入左边，所有之后不会重复计算小和。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">smallSum</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (arr == <span class="keyword">null</span> || arr.length &lt; <span class="number">2</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> mergeSort(arr, <span class="number">0</span>, arr.length - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">mergeSort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> l, <span class="keyword">int</span> r)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (l == r) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> mid = l + ((r - l) &gt;&gt; <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> mergeSort(arr, l, mid) + mergeSort(arr, mid + <span class="number">1</span>, r) + merge(arr, l, mid, r);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">merge</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> l, <span class="keyword">int</span> m, <span class="keyword">int</span> r)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[] help = <span class="keyword">new</span> <span class="keyword">int</span>[r - l + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">int</span> p1 = l;</span><br><span class="line">	<span class="keyword">int</span> p2 = m + <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">while</span> (p1 &lt;= m &amp;&amp; p2 &lt;= r) &#123;</span><br><span class="line">	    <span class="comment">//计算小和</span></span><br><span class="line">		res += arr[p1] &lt; arr[p2] ? (r - p2 + <span class="number">1</span>) * arr[p1] : <span class="number">0</span>;</span><br><span class="line">		help[i++] = arr[p1] &lt; arr[p2] ? arr[p1++] : arr[p2++];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (p1 &lt;= m) &#123;</span><br><span class="line">		help[i++] = arr[p1++];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (p2 &lt;= r) &#123;</span><br><span class="line">		help[i++] = arr[p2++];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; help.length; i++) &#123;</span><br><span class="line">		arr[l + i] = help[i];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="逆序对问题"><a href="#逆序对问题" class="headerlink" title="逆序对问题"></a>逆序对问题</h2><p>在一个数组中， 左边的数如果比右边的数大， 则折两个数构成一个逆序对， 请打印所有逆序<br>对。</p>
<p><strong>题解：</strong></p>
<p>与上题解题思路一致。将计算小和改为判断 arr[p1] &gt; arr[p2] 如果是，则打印 arr[p1], arr[p2]即可。</p>
<h2 id="相邻两数的最大差值"><a href="#相邻两数的最大差值" class="headerlink" title="相邻两数的最大差值"></a>相邻两数的最大差值</h2><p>给定一个数组， 求如果排序之后， 相邻两数的最大差值。</p>
<p>要求时间复杂度O(N),且要求不能用非基于比较的排序。</p>
<p><strong>题解：</strong></p>
<p>使用桶排序的概念，在此基础上进行优化。</p>
<ol>
<li>遍历给定的数组，找到数组中的最大值、最小值(最大值等于最小值时说明，数组中数据都一样，返回 0 ),用于计算桶id。</li>
<li>准备n+1 个桶，对于每个桶中的元素设定三个标志位。是否有数据 hasNum、最大值 maxs、最小值 mins。</li>
<li>再次遍历标志位。第0 个桶一定非空，且为最小值。从第一个桶开始遍历，找到每个非空桶(hasNum[i] 为 true)，非空桶的最小值与它前边最近的非空桶的最大值 作差，与全局变量res作比较。遍历结束之后将得到最大的差值。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">maxGap</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (nums == <span class="keyword">null</span> || nums.length &lt; <span class="number">2</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> len = nums.length;</span><br><span class="line">	<span class="keyword">int</span> min = Integer.MAX_VALUE;</span><br><span class="line">	<span class="keyword">int</span> max = Integer.MIN_VALUE;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">		min = Math.min(min, nums[i]);</span><br><span class="line">		max = Math.max(max, nums[i]);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 如果最小值等于最大值，则数组中只有相同的数，最大差值为 0.</span></span><br><span class="line">	<span class="keyword">if</span> (min == max) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 计算每个桶中的三个标志位。</span></span><br><span class="line">	<span class="keyword">boolean</span>[] hasNum = <span class="keyword">new</span> <span class="keyword">boolean</span>[len + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">int</span>[] maxs = <span class="keyword">new</span> <span class="keyword">int</span>[len + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">int</span>[] mins = <span class="keyword">new</span> <span class="keyword">int</span>[len + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">int</span> bid = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">		bid = bucket(nums[i], len, min, max);</span><br><span class="line">		mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums</span><br><span class="line">		maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums</span><br><span class="line">		hasNum[bid] = <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 从第一个桶开始。寻找不为空的桶，它的最小值和它之前最近的桶的最大值的差值，</span></span><br><span class="line">	<span class="comment">// 与全局变量res进行比较，遍历完则找到最大差值。</span></span><br><span class="line">	<span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">int</span> lastMax = maxs[<span class="number">0</span>];</span><br><span class="line">	<span class="keyword">int</span> i = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">for</span> (; i &lt;= len; i++) &#123;</span><br><span class="line">		<span class="keyword">if</span> (hasNum[i]) &#123;</span><br><span class="line">			res = Math.max(res, mins[i] - lastMax);</span><br><span class="line">			lastMax = maxs[i];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 最小值将存在0号桶，最大值将存在length号桶。</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">bucket</span><span class="params">(<span class="keyword">long</span> num, <span class="keyword">long</span> len, <span class="keyword">long</span> min, <span class="keyword">long</span> max)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> (<span class="keyword">int</span>) ((num - min) * len / (max - min));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="栈和队列"><a href="#栈和队列" class="headerlink" title="栈和队列"></a>栈和队列</h1><h2 id="数组实现固定大小的队列和栈"><a href="#数组实现固定大小的队列和栈" class="headerlink" title="数组实现固定大小的队列和栈"></a>数组实现固定大小的队列和栈</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.array;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Array2QueueStack</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 数组实现队列 测试</span></span><br><span class="line">        AQueue aQueue = <span class="keyword">new</span> AQueue(<span class="number">3</span>);</span><br><span class="line">        aQueue.offer(<span class="number">1</span>);</span><br><span class="line">        aQueue.offer(<span class="number">2</span>);</span><br><span class="line">        aQueue.offer(<span class="number">3</span>);</span><br><span class="line">        aQueue.offer(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(aQueue.poll());</span><br><span class="line"></span><br><span class="line">        aQueue.offer(<span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(aQueue.peek());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 数组实现栈 测试</span></span><br><span class="line">        AStack aStack = <span class="keyword">new</span> AStack(<span class="number">3</span>);</span><br><span class="line">        aStack.push(<span class="number">1</span>);</span><br><span class="line">        aStack.push(<span class="number">2</span>);</span><br><span class="line">        aStack.push(<span class="number">3</span>);</span><br><span class="line">        aStack.push(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(aStack.pop());</span><br><span class="line"></span><br><span class="line">        aStack.push(<span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(aStack.peek());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 数组实现大小固定的队列。</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * arr：存储队列中的数据。</span></span><br><span class="line"><span class="comment"> * size：记录队列中有多少数据了。</span></span><br><span class="line"><span class="comment"> * start：记录出队列的位置。每次出start位置上的数据。</span></span><br><span class="line"><span class="comment"> * end：记录入队列的位置。每次入队列存入end的位置。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AQueue</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] arr;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> start;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> end;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AQueue</span><span class="params">(<span class="keyword">int</span> initSize)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.arr = <span class="keyword">new</span> <span class="keyword">int</span>[initSize];</span><br><span class="line">        <span class="keyword">this</span>.size = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.start = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.end = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">offer</span><span class="params">(Integer n)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == arr.length) &#123;</span><br><span class="line">            System.out.println(<span class="string">"queue is full!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        size++;</span><br><span class="line">        arr[end] = n;</span><br><span class="line">        end = end == arr.length - <span class="number">1</span> ? <span class="number">0</span> : end + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">poll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"queue is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        size--;</span><br><span class="line">        <span class="keyword">int</span> tmp = arr[start];</span><br><span class="line">        start = start == arr.length - <span class="number">1</span> ? <span class="number">0</span> : start + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> tmp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">peek</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"queue is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> arr[start];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 数组实现大小固定的栈。</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * arr：存储栈中的数据。</span></span><br><span class="line"><span class="comment"> * size：栈中存储多少数据。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AStack</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] arr;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AStack</span><span class="params">(<span class="keyword">int</span> initSize)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.arr = <span class="keyword">new</span> <span class="keyword">int</span>[initSize];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">push</span><span class="params">(Integer n)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == arr.length) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is full!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        arr[size++] = n;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">pop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> arr[--size];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">peek</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (size == <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> arr[size - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="实现返回栈中最小元素"><a href="#实现返回栈中最小元素" class="headerlink" title="实现返回栈中最小元素"></a>实现返回栈中最小元素</h2><p>实现一个特殊的栈， 在实现栈的基本功能的基础上， 再实现返<br>回栈中最小元素的操作。</p>
<h3 id="要求"><a href="#要求" class="headerlink" title="要求"></a>要求</h3><ol>
<li>pop、 push、 getMin操作的时间复杂度都是O(1)。</li>
<li>设计的栈类型可以使用现成的栈结构。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.array;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Stack;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetMinStack</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        MyStack myStack = <span class="keyword">new</span> MyStack();</span><br><span class="line">        myStack.push(<span class="number">5</span>);</span><br><span class="line">        myStack.push(<span class="number">1</span>);</span><br><span class="line">        System.out.println(myStack.getMin());</span><br><span class="line">        System.out.println(myStack.pop());</span><br><span class="line">        myStack.push(<span class="number">3</span>);</span><br><span class="line">        myStack.push(<span class="number">8</span>);</span><br><span class="line">        System.out.println(myStack.getMin());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 可以返回栈中最小元素的栈。</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * pop、 push、 getMin操作的时间复杂度都是O(1)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyStack</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; stackData;</span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; stackMin;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyStack</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.stackData = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.stackMin = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">push</span><span class="params">(Integer n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 最小值栈中没有数据直接进栈。</span></span><br><span class="line">        <span class="comment">// 栈中有数据判断插入数据n 是否小于当前栈中最小值，小则插入n，否则再次插入栈中最小值 </span></span><br><span class="line">        <span class="keyword">if</span> (stackMin.isEmpty()) &#123;</span><br><span class="line">            stackMin.push(n);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (n &lt;= getMin()) &#123;</span><br><span class="line">            stackMin.push(n);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            stackMin.push(getMin());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        stackData.push(n);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">pop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (stackData.isEmpty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 弹栈时，数据栈和最小值栈同时弹出。</span></span><br><span class="line">        stackMin.pop();</span><br><span class="line">        <span class="keyword">return</span> stackData.pop();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getMin</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (stackMin.isEmpty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> stackMin.peek();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="如何仅用队列结构实现栈结构？"><a href="#如何仅用队列结构实现栈结构？" class="headerlink" title="如何仅用队列结构实现栈结构？"></a>如何仅用队列结构实现栈结构？</h2><p>见下题</p>
<h2 id="如何仅用栈结构实现队列结构？"><a href="#如何仅用栈结构实现队列结构？" class="headerlink" title="如何仅用栈结构实现队列结构？"></a>如何仅用栈结构实现队列结构？</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.stack;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.LinkedList;</span><br><span class="line"><span class="keyword">import</span> java.util.Queue;</span><br><span class="line"><span class="keyword">import</span> java.util.Stack;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StackAndQueueConvert</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 栈实现队列，应打印 1,2</span></span><br><span class="line">        Stack2Queue stack2Queue = <span class="keyword">new</span> Stack2Queue();</span><br><span class="line">        stack2Queue.offer(<span class="number">1</span>);</span><br><span class="line">        stack2Queue.offer(<span class="number">2</span>);</span><br><span class="line">        stack2Queue.offer(<span class="number">3</span>);</span><br><span class="line">        System.out.println(stack2Queue.poll());</span><br><span class="line">        stack2Queue.offer(<span class="number">4</span>);</span><br><span class="line">        stack2Queue.offer(<span class="number">5</span>);</span><br><span class="line">        System.out.println(stack2Queue.peek());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"----------------------"</span>);</span><br><span class="line">        <span class="comment">// 队列实现栈，应打印 3,5</span></span><br><span class="line">        Queue2Stack queue2Stack = <span class="keyword">new</span> Queue2Stack();</span><br><span class="line">        queue2Stack.push(<span class="number">1</span>);</span><br><span class="line">        queue2Stack.push(<span class="number">2</span>);</span><br><span class="line">        queue2Stack.push(<span class="number">3</span>);</span><br><span class="line">        System.out.println(queue2Stack.pop());</span><br><span class="line">        queue2Stack.push(<span class="number">4</span>);</span><br><span class="line">        queue2Stack.push(<span class="number">5</span>);</span><br><span class="line">        System.out.println(queue2Stack.peek());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 两个栈实现队列</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 入队列栈中数据倒入出队列栈中的数据时，要保证出队列栈中无数据。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Stack2Queue</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; in;</span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; out;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Stack2Queue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.in = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.out = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">offer</span><span class="params">(Integer n)</span> </span>&#123;</span><br><span class="line">        in.push(n);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">poll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (out.empty() &amp;&amp; in.empty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"queue is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (out.empty()) &#123;</span><br><span class="line">            <span class="keyword">while</span> (!in.empty()) &#123;</span><br><span class="line">                out.push(in.pop());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> out.pop();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">peek</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (out.empty() &amp;&amp; in.empty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"queue is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (out.empty()) &#123;</span><br><span class="line">            <span class="keyword">while</span> (!in.empty()) &#123;</span><br><span class="line">                out.push(in.pop());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> out.peek();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 两个队列实现栈</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 入栈直接放入stack这个队列中。</span></span><br><span class="line"><span class="comment"> * 每次出栈，将n-1个数据通过help队列保存，返回第n个数据，然后改变help、stack指针 即可。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Queue2Stack</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Queue&lt;Integer&gt; stack;</span><br><span class="line">    <span class="keyword">private</span> Queue&lt;Integer&gt; help;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Queue2Stack</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.stack = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.help = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">push</span><span class="params">(Integer n)</span> </span>&#123;</span><br><span class="line">        stack.offer(n);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">pop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (stack.isEmpty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (stack.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">            help.offer(stack.poll());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> res = stack.poll();</span><br><span class="line">        swap();</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">swap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Queue&lt;Integer&gt; tmp = help;</span><br><span class="line">        help = stack;</span><br><span class="line">        stack = tmp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">peek</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (stack.isEmpty()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"stack is empty!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (stack.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">            help.offer(stack.poll());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> res = stack.poll();</span><br><span class="line">        <span class="comment">// peek 不删除，需加上res</span></span><br><span class="line">        help.offer(res);</span><br><span class="line"></span><br><span class="line">        swap();</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="猫狗队列"><a href="#猫狗队列" class="headerlink" title="猫狗队列"></a>猫狗队列</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String type;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Pet</span><span class="params">(String type)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.type = type;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPetType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.type;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Dog</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="string">"dog"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> <span class="keyword">extends</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="string">"cat"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现一种狗猫队列的结构， </p>
<h3 id="要求-1"><a href="#要求-1" class="headerlink" title="要求"></a>要求</h3><ul>
<li>用户可以调用add方法将cat类或dog类的实例放入队列中；</li>
<li>用户可以调用pollAll方法，将队列中所有的实例按照进队列的先后顺序依次弹出；</li>
<li>用户可以调用pollDog方法，将队列中dog类的实例按照进队列的先后顺序依次弹出；</li>
<li>用户可以调用pollCat方法，将队列中cat类的实例按照进队列的先后顺序依次弹出；</li>
<li>用户可以调用isEmpty方法， 检查队列中是<br>否还有dog或cat的实例；</li>
<li>用户可以调用isDogEmpty方法，检查队列中是否有dog类的实例； </li>
<li>用户可以调用isCatEmpty方法， 检查队列中是否有cat类的实例。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.queue;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.LinkedList;</span><br><span class="line"><span class="keyword">import</span> java.util.Queue;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CatDogQueue</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Queue&lt;PetEntity&gt; catQ;</span><br><span class="line">    <span class="keyword">private</span> Queue&lt;PetEntity&gt; dogQ;</span><br><span class="line">    <span class="keyword">private</span> Long count;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CatDogQueue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.catQ = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.dogQ = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.count = <span class="number">0L</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(Pet pet)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (pet.getPetType().equals(<span class="string">"cat"</span>)) &#123;</span><br><span class="line">            catQ.add(<span class="keyword">new</span> PetEntity(pet, <span class="keyword">this</span>.count++));</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (pet.getPetType().equals(<span class="string">"dog"</span>)) &#123;</span><br><span class="line">            dogQ.add(<span class="keyword">new</span> PetEntity(pet, <span class="keyword">this</span>.count++));</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"NOT cat or dog!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Pet <span class="title">pollAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!catQ.isEmpty() &amp;&amp; !dogQ.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (catQ.peek().getCount() &lt; dogQ.peek().getCount()) &#123;</span><br><span class="line">                <span class="keyword">return</span> catQ.poll().getPet();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> dogQ.poll().getPet();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!catQ.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">return</span> catQ.poll().getPet();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!dogQ.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">return</span> dogQ.poll().getPet();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"queue is empty!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Cat <span class="title">pollCat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (catQ.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"queue is empty!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> (Cat) catQ.poll().getPet();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Dog <span class="title">pollDog</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (dogQ.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"queue is empty!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> (Dog) dogQ.poll().getPet();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> catQ.isEmpty() &amp;&amp; dogQ.isEmpty();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isCatQueueEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> catQ.isEmpty();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isDogQueueEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> dogQ.isEmpty();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CatDogQueue test = <span class="keyword">new</span> CatDogQueue();</span><br><span class="line"></span><br><span class="line">        Pet dog1 = <span class="keyword">new</span> Dog();</span><br><span class="line">        Pet cat1 = <span class="keyword">new</span> Cat();</span><br><span class="line">        Pet dog2 = <span class="keyword">new</span> Dog();</span><br><span class="line">        Pet cat2 = <span class="keyword">new</span> Cat();</span><br><span class="line">        Pet dog3 = <span class="keyword">new</span> Dog();</span><br><span class="line">        Pet cat3 = <span class="keyword">new</span> Cat();</span><br><span class="line"></span><br><span class="line">        test.add(dog1);</span><br><span class="line">        test.add(cat1);</span><br><span class="line">        test.add(dog2);</span><br><span class="line">        test.add(cat2);</span><br><span class="line">        test.add(dog3);</span><br><span class="line">        test.add(cat3);</span><br><span class="line"></span><br><span class="line">        test.add(dog1);</span><br><span class="line">        test.add(cat1);</span><br><span class="line">        test.add(dog2);</span><br><span class="line">        test.add(cat2);</span><br><span class="line">        test.add(dog3);</span><br><span class="line">        test.add(cat3);</span><br><span class="line"></span><br><span class="line">        test.add(dog1);</span><br><span class="line">        test.add(cat1);</span><br><span class="line">        test.add(dog2);</span><br><span class="line">        test.add(cat2);</span><br><span class="line">        test.add(dog3);</span><br><span class="line">        test.add(cat3);</span><br><span class="line">        <span class="keyword">while</span> (!test.isDogQueueEmpty()) &#123;</span><br><span class="line">            System.out.println(test.pollDog().getPetType());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (!test.isEmpty()) &#123;</span><br><span class="line">            System.out.println(test.pollAll().getPetType());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String type;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Pet</span><span class="params">(String type)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.type = type;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPetType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.type;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Dog</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="string">"dog"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cat</span> <span class="keyword">extends</span> <span class="title">Pet</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="string">"cat"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PetEntity</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Pet pet;</span><br><span class="line">    <span class="keyword">private</span> Long count;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PetEntity</span><span class="params">(Pet pet, Long count)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pet = pet;</span><br><span class="line">        <span class="keyword">this</span>.count = count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Pet <span class="title">getPet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> pet;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="矩阵"><a href="#矩阵" class="headerlink" title="矩阵"></a>矩阵</h1><h2 id="转圈打印矩阵"><a href="#转圈打印矩阵" class="headerlink" title="转圈打印矩阵"></a>转圈打印矩阵</h2><p>给定一个整型矩阵matrix， 请按照转圈的方式打印它。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">例如：</span><br><span class="line">1   2   3   4</span><br><span class="line">5   6   7   8</span><br><span class="line">9  10  11  12</span><br><span class="line">13 14  15  16 </span><br><span class="line"></span><br><span class="line">打印结果为： </span><br><span class="line">1，2，3，4，8，12，16，15，14，13，9，5，6，7，11，10</span><br></pre></td></tr></table></figure>

<h3 id="要求-2"><a href="#要求-2" class="headerlink" title="要求"></a>要求</h3><p>额外空间复杂度为O(1)。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.matrix;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RotateMatrix</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[][] matrix = &#123;&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;, &#123;<span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>&#125;, &#123;<span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>&#125;, &#123;<span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>, <span class="number">16</span>&#125;&#125;;</span><br><span class="line">        <span class="keyword">int</span>[][] matrix1 = &#123;&#123;<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">8</span>, <span class="number">0</span>&#125;&#125;;</span><br><span class="line">        rotate(matrix);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 旋转打印</span></span><br><span class="line"><span class="comment">     * 每次层数减一，像剥洋葱一样，一次一层。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 矩阵</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">spiralOrderPrint</span><span class="params">(<span class="keyword">int</span>[][] matrix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> ar = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> ac = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> br = matrix.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> bc = matrix[<span class="number">0</span>].length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (ar &lt;= br &amp;&amp; ac &lt;= bc) &#123;</span><br><span class="line">            printEdge(matrix, ar++, ac++, br--, bc--);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 顺时针打印矩阵的环</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 待打印的矩阵</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ar     左上角行数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ac     左上角列数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> br     右下角行数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bc     右下角列数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printEdge</span><span class="params">(<span class="keyword">int</span>[][] matrix, <span class="keyword">int</span> ar, <span class="keyword">int</span> ac, <span class="keyword">int</span> br, <span class="keyword">int</span> bc)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (ar == br) &#123;</span><br><span class="line">            <span class="comment">// 只有一行</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = ac; i &lt;= bc; i++) &#123;</span><br><span class="line">                System.out.print(matrix[ar][i] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ac == bc) &#123;</span><br><span class="line">            <span class="comment">// 只有一列</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = ar; i &lt;= br; i++) &#123;</span><br><span class="line">                System.out.print(matrix[i][ac] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> curR = ar;</span><br><span class="line">            <span class="keyword">int</span> curC = ac;</span><br><span class="line">            <span class="keyword">while</span> (curC &lt; bc) &#123;</span><br><span class="line">                System.out.print(matrix[curR][curC++] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (curR &lt; br) &#123;</span><br><span class="line">                System.out.print(matrix[curR++][curC] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (curC &gt; ac) &#123;</span><br><span class="line">                System.out.print(matrix[curR][curC--] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (curR &gt; ar) &#123;</span><br><span class="line">                System.out.print(matrix[curR--][curC] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="旋转正方形矩阵"><a href="#旋转正方形矩阵" class="headerlink" title="旋转正方形矩阵"></a>旋转正方形矩阵</h2><p>给定一个整型正方形矩阵matrix，请把该矩阵调整成<br>顺时针旋转90度的样子。</p>
<h3 id="要求-3"><a href="#要求-3" class="headerlink" title="要求"></a>要求</h3><p>额外空间复杂度为O(1)。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.matrix;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 旋转正方形矩阵</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RotateMatrix</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[][] matrix = &#123;&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;, &#123;<span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>&#125;, &#123;<span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>&#125;, &#123;<span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>, <span class="number">16</span>&#125;&#125;;</span><br><span class="line">        printMatrix(matrix);</span><br><span class="line">        rotate(matrix);</span><br><span class="line">        System.out.println(<span class="string">"======================="</span>);</span><br><span class="line">        printMatrix(matrix);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 顺时针旋转矩阵</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 矩阵</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">rotate</span><span class="params">(<span class="keyword">int</span>[][] matrix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> ar = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> ac = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> br = matrix.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> bc = matrix[<span class="number">0</span>].length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (ar &lt; br) &#123;</span><br><span class="line">            rotateEdge(matrix, ar++, ac++, br--, bc--);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 转动矩阵边缘</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 待转动的矩阵</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ar     矩阵左上角行。</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ac     矩阵左上角列。</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> br     矩阵右下角行。</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bc     矩阵右下角列。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">rotateEdge</span><span class="params">(<span class="keyword">int</span>[][] matrix, <span class="keyword">int</span> ar, <span class="keyword">int</span> ac, <span class="keyword">int</span> br, <span class="keyword">int</span> bc)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> times = bc - ac;</span><br><span class="line">        <span class="keyword">int</span> tmp = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            tmp = matrix[ar][ac + i];</span><br><span class="line">            matrix[ar][ac + i] = matrix[br - i][ac];</span><br><span class="line">            matrix[br - i][ac] = matrix[br][bc - i];</span><br><span class="line">            matrix[br][bc - i] = matrix[ar + i][bc];</span><br><span class="line">            matrix[ar + i][bc] = tmp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 打印矩阵当前状态</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 矩阵</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printMatrix</span><span class="params">(<span class="keyword">int</span>[][] matrix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; matrix.length; i++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; matrix[i].length; j++) &#123;</span><br><span class="line">                System.out.print(matrix[i][j] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="反转单向和双向链表"><a href="#反转单向和双向链表" class="headerlink" title="反转单向和双向链表"></a>反转单向和双向链表</h2><p>分别实现反转单向链表和反转双向链表的函数。</p>
<h3 id="要求-4"><a href="#要求-4" class="headerlink" title="要求"></a>要求</h3><p>如果链表长度为N， 时间复杂度要求为O(N)， 额外空间复杂度要求为O(1)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;                 </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> value;                      </span><br><span class="line">    <span class="keyword">public</span> Node next;                      </span><br><span class="line">                                           </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123;                </span><br><span class="line">        <span class="keyword">this</span>.value = data;                 </span><br><span class="line">    &#125;                                      </span><br><span class="line">&#125;                                          </span><br><span class="line">                                           </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Node <span class="title">reverseList</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">    Node pre = <span class="keyword">null</span>;                       </span><br><span class="line">    Node next = <span class="keyword">null</span>;                      </span><br><span class="line">    <span class="keyword">while</span> (head != <span class="keyword">null</span>) &#123;                 </span><br><span class="line">        next = head.next;                  </span><br><span class="line">        head.next = pre;                   </span><br><span class="line">        pre = head;                        </span><br><span class="line">        head = next;                       </span><br><span class="line">    &#125;                                      </span><br><span class="line">    <span class="keyword">return</span> pre;                            </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="“之”-字形打印矩阵"><a href="#“之”-字形打印矩阵" class="headerlink" title="“之” 字形打印矩阵"></a>“之” 字形打印矩阵</h2><p>给定一个矩阵matrix， 按照“之” 字形的方式打印这<br>个矩阵， </p>
<p>例如： 1 2 3 4 5 6 7 8 9 10 11 12</p>
<p>“之” 字形打印的结果为： 1， 2， 5， 9， 6， 3， 4， 7， 10， 11，8， 12</p>
<h3 id="要求-5"><a href="#要求-5" class="headerlink" title="要求"></a>要求</h3><p>额外空间复杂度为O(1)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.matrix;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintMatrixZig</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printMatrixZigZag</span><span class="params">(<span class="keyword">int</span>[][] matrix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> ar = <span class="number">0</span>, ac = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> br = <span class="number">0</span>, bc = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> endR = matrix.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> endC = matrix[<span class="number">0</span>].length - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> fromUp = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (br &lt;= endR) &#123;</span><br><span class="line">            printSlash(matrix, ar, ac, br, bc, fromUp);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 下面四个顺序很重要，修改判断条件的操作放在后边</span></span><br><span class="line">            ac = ar == endR ? ac + <span class="number">1</span> : ac;</span><br><span class="line">            ar = ar == endR ? ar : ar + <span class="number">1</span>;</span><br><span class="line">            br = bc == endC ? br + <span class="number">1</span> : br;</span><br><span class="line">            bc = bc == endC ? bc : bc + <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">            fromUp = !fromUp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 打印斜线</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 二维数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ar     a点横坐标</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ac     a点纵坐标</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> br     b点横坐标</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bc     b点纵坐标</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> f      是否为从上到下</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printSlash</span><span class="params">(<span class="keyword">int</span>[][] matrix, <span class="keyword">int</span> ar, <span class="keyword">int</span> ac, <span class="keyword">int</span> br, <span class="keyword">int</span> bc, <span class="keyword">boolean</span> f)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (f) &#123;</span><br><span class="line">            <span class="keyword">while</span> (ar &gt;= br) &#123;</span><br><span class="line">                System.out.print(matrix[br++][bc--] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (ar &gt;= br) &#123;</span><br><span class="line">                System.out.print(matrix[ar--][ac++] + <span class="string">" "</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[][] matrix = &#123;&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;, &#123;<span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>&#125;, &#123;<span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>&#125;, &#123;<span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>, <span class="number">16</span>&#125;&#125;;</span><br><span class="line">        printMatrixZigZag(matrix);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="在行列都排好序的矩阵中找数"><a href="#在行列都排好序的矩阵中找数" class="headerlink" title="在行列都排好序的矩阵中找数"></a>在行列都排好序的矩阵中找数</h2><p>给定一个有N*M的整型矩阵matrix和一个整数K，<br>matrix的每一行和每一 列都是排好序的。 实现一个函数， 判断K<br>是否在matrix中。 </p>
<p>例如： 0 1 2 5 2 3 4 7 4<br>4 4 8 5 7 7 9 如果K为7， 返回true； 如果K为6， 返回false。</p>
<h3 id="要求-6"><a href="#要求-6" class="headerlink" title="要求"></a>要求</h3><p>时间复杂度为O(N+M)， 额外空间复杂度为O(1)。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.matrix;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FindNumInSortedMatrix</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[][] matrix = <span class="keyword">new</span> <span class="keyword">int</span>[][]&#123;&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>&#125;,<span class="comment">// 0</span></span><br><span class="line">                &#123;<span class="number">10</span>, <span class="number">12</span>, <span class="number">13</span>, <span class="number">15</span>, <span class="number">16</span>, <span class="number">17</span>, <span class="number">18</span>&#125;,<span class="comment">// 1</span></span><br><span class="line">                &#123;<span class="number">23</span>, <span class="number">24</span>, <span class="number">25</span>, <span class="number">26</span>, <span class="number">27</span>, <span class="number">28</span>, <span class="number">29</span>&#125;,<span class="comment">// 2</span></span><br><span class="line">                &#123;<span class="number">44</span>, <span class="number">45</span>, <span class="number">46</span>, <span class="number">47</span>, <span class="number">48</span>, <span class="number">49</span>, <span class="number">50</span>&#125;,<span class="comment">// 3</span></span><br><span class="line">                &#123;<span class="number">65</span>, <span class="number">66</span>, <span class="number">67</span>, <span class="number">68</span>, <span class="number">69</span>, <span class="number">70</span>, <span class="number">71</span>&#125;,<span class="comment">// 4</span></span><br><span class="line">                &#123;<span class="number">96</span>, <span class="number">97</span>, <span class="number">98</span>, <span class="number">99</span>, <span class="number">100</span>, <span class="number">111</span>, <span class="number">122</span>&#125;,<span class="comment">// 5</span></span><br><span class="line">                &#123;<span class="number">166</span>, <span class="number">176</span>, <span class="number">186</span>, <span class="number">187</span>, <span class="number">190</span>, <span class="number">195</span>, <span class="number">200</span>&#125;,<span class="comment">// 6</span></span><br><span class="line">                &#123;<span class="number">233</span>, <span class="number">243</span>, <span class="number">321</span>, <span class="number">341</span>, <span class="number">356</span>, <span class="number">370</span>, <span class="number">380</span>&#125; <span class="comment">// 7</span></span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">int</span> K = <span class="number">233</span>;</span><br><span class="line">        System.out.println(isContains(matrix, K));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查找思路，从右上角进行查找</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> matrix 矩阵</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> k      查找的key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> Boolean</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isContains</span><span class="params">(<span class="keyword">int</span>[][] matrix, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> r = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> c = matrix[<span class="number">0</span>].length - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 行要小于矩阵的行数。列要大于-1.</span></span><br><span class="line">        <span class="keyword">while</span> (r &lt; matrix.length &amp;&amp; c &gt; -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (matrix[r][c] == k) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (matrix[r][c] &gt; k) &#123;</span><br><span class="line">                c--;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                r++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="链表"><a href="#链表" class="headerlink" title="链表"></a>链表</h1><h2 id="打印两个有序链表的公共节点"><a href="#打印两个有序链表的公共节点" class="headerlink" title="打印两个有序链表的公共节点"></a>打印两个有序链表的公共节点</h2><p>给定两个有序链表的头指针head1和head2， 打印两<br>链表的公共节点</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.list.s;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.jelly.algorithm.list.ListNode;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 打印两个有序链表的公共节点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintCommonPart</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printCommonPart</span><span class="params">(ListNode head1, ListNode head2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (head1 != <span class="keyword">null</span> &amp;&amp; head2 != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (head1.val &lt; head2.val) &#123;</span><br><span class="line">                head1 = head1.next;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (head1.val &gt; head2.val) &#123;</span><br><span class="line">                head2 = head2.next;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.print(head1.val + <span class="string">" "</span>);</span><br><span class="line">                head1 = head1.next;</span><br><span class="line">                head2 = head2.next;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printLinkedList</span><span class="params">(ListNode node)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"node: "</span>);</span><br><span class="line">        <span class="keyword">while</span> (node != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.print(node.val + <span class="string">" "</span>);</span><br><span class="line">            node = node.next;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ListNode node1 = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        node1.next = <span class="keyword">new</span> ListNode(<span class="number">3</span>);</span><br><span class="line">        node1.next.next = <span class="keyword">new</span> ListNode(<span class="number">5</span>);</span><br><span class="line">        node1.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">        ListNode node2 = <span class="keyword">new</span> ListNode(<span class="number">1</span>);</span><br><span class="line">        node2.next = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        node2.next.next = <span class="keyword">new</span> ListNode(<span class="number">5</span>);</span><br><span class="line">        node2.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">7</span>);</span><br><span class="line">        node2.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">8</span>);</span><br><span class="line"></span><br><span class="line">        printLinkedList(node1);</span><br><span class="line">        printLinkedList(node2);</span><br><span class="line">        printCommonPart(node1, node2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="判断一个链表是否为回文结构"><a href="#判断一个链表是否为回文结构" class="headerlink" title="判断一个链表是否为回文结构"></a>判断一个链表是否为回文结构</h2><p>给定一个链表的头节点head，请判断该链表是否为回文结构。 </p>
<p>例如： </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">1-&gt;2-&gt;1， 返回true。 </span><br><span class="line">1-&gt;2-&gt;2-&gt;1，返回true。</span><br><span class="line">15-&gt;6-&gt;15， 返回true。 </span><br><span class="line">1-&gt;2-&gt;3， 返回false。</span><br></pre></td></tr></table></figure>

<p>进阶： 如果链表长度为N， 时间复杂度达到O(N)， 额外空间复杂度达到O(1)。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.list.s;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.jelly.algorithm.list.ListNode;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Stack;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> V1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@program</span>: study-leetcode</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 判断链表是否为回文链表</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019-10-27 14:35</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IsPalindrome</span> </span>&#123;</span><br><span class="line">    <span class="comment">// need n extra space</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isPalindrome1</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">        Stack&lt;ListNode&gt; stack = <span class="keyword">new</span> Stack&lt;ListNode&gt;();</span><br><span class="line">        ListNode cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            stack.push(cur);</span><br><span class="line">            cur = cur.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (head != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (head.val != stack.pop().val) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            head = head.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// need n/2 extra space</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isPalindrome2</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head == <span class="keyword">null</span> || head.next == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ListNode right = head.next;</span><br><span class="line">        ListNode cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur.next != <span class="keyword">null</span> &amp;&amp; cur.next.next != <span class="keyword">null</span>) &#123;</span><br><span class="line">            right = right.next;</span><br><span class="line">            cur = cur.next.next;</span><br><span class="line">        &#125;</span><br><span class="line">        Stack&lt;ListNode&gt; stack = <span class="keyword">new</span> Stack&lt;ListNode&gt;();</span><br><span class="line">        <span class="keyword">while</span> (right != <span class="keyword">null</span>) &#123;</span><br><span class="line">            stack.push(right);</span><br><span class="line">            right = right.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (head.val != stack.pop().val) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            head = head.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// need O(1) extra space</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isPalindrome</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head == <span class="keyword">null</span> || head.next == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// find mid. n1 point mid after loop</span></span><br><span class="line">        ListNode n1 = head;</span><br><span class="line">        ListNode n2 = head;</span><br><span class="line">        <span class="keyword">while</span> (n2.next != <span class="keyword">null</span> &amp;&amp; n2.next.next != <span class="keyword">null</span>) &#123; <span class="comment">// find mid ListNode</span></span><br><span class="line">            n1 = n1.next;</span><br><span class="line">            n2 = n2.next.next;</span><br><span class="line">        &#125;</span><br><span class="line">        n2 = n1.next; <span class="comment">// n2 -&gt; right part first ListNode</span></span><br><span class="line">        n1.next = <span class="keyword">null</span>; <span class="comment">// mid.next -&gt; null</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// reverse second half</span></span><br><span class="line">        ListNode n3 = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">while</span> (n2 != <span class="keyword">null</span>) &#123;</span><br><span class="line">            n3 = n2.next;</span><br><span class="line">            n2.next = n1;</span><br><span class="line">            n1 = n2;</span><br><span class="line">            n2 = n3;</span><br><span class="line">        &#125;</span><br><span class="line">        n3 = n1; <span class="comment">// n3 -&gt; save last ListNode</span></span><br><span class="line">        n2 = head;<span class="comment">// n2 -&gt; left first ListNode</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// check palindrome</span></span><br><span class="line">        <span class="keyword">boolean</span> res = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">while</span> (n1 != <span class="keyword">null</span> &amp;&amp; n2 != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (n1.val != n2.val) &#123;</span><br><span class="line">                res = <span class="keyword">false</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            n1 = n1.next; <span class="comment">// left to mid</span></span><br><span class="line">            n2 = n2.next; <span class="comment">// right to mid</span></span><br><span class="line">        &#125;</span><br><span class="line">        n1 = n3.next;</span><br><span class="line">        n3.next = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// recover list</span></span><br><span class="line">        <span class="keyword">while</span> (n1 != <span class="keyword">null</span>) &#123;</span><br><span class="line">            n2 = n1.next;</span><br><span class="line">            n1.next = n3;</span><br><span class="line">            n3 = n1;</span><br><span class="line">            n1 = n2;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ListNode head = <span class="keyword">new</span> ListNode(<span class="number">1</span>);</span><br><span class="line">        ListNode node2 = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        ListNode node3 = <span class="keyword">new</span> ListNode(<span class="number">3</span>);</span><br><span class="line">        ListNode node4 = <span class="keyword">new</span> ListNode(<span class="number">4</span>);</span><br><span class="line">        ListNode node5 = <span class="keyword">new</span> ListNode(<span class="number">3</span>);</span><br><span class="line">        ListNode node6 = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        ListNode node7 = <span class="keyword">new</span> ListNode(<span class="number">1</span>);</span><br><span class="line">        head.next = node2;</span><br><span class="line">        node2.next = node3;</span><br><span class="line">        node3.next = node4;</span><br><span class="line">        node4.next = node5;</span><br><span class="line">        node5.next = node6;</span><br><span class="line">        node6.next = node7;</span><br><span class="line">        System.out.println(isPalindrome(head));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="将单向链表按某值划分成左边小、-中间相等、-右边大的形式"><a href="#将单向链表按某值划分成左边小、-中间相等、-右边大的形式" class="headerlink" title="将单向链表按某值划分成左边小、 中间相等、 右边大的形式"></a>将单向链表按某值划分成左边小、 中间相等、 右边大的形式</h2><p>给定一个单向链表的头节点head，节点的值类型是整型，再给定一个整 数pivot。 </p>
<p>实现一个调整链表的函数，将链表调整为左部分都是值小于 pivot的节点，中间部分都是值等于pivot的节点， 右部分都是值大于 pivot的节点。<br>除这个要求外，对调整后的节点顺序没有更多的要求。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">例如： </span><br><span class="line">链表 9-&gt;0-&gt;4-&gt;5-&gt;1， pivot=3。 </span><br><span class="line"></span><br><span class="line">调整后链表可以是 1-&gt;0-&gt;4-&gt;9-&gt;5，</span><br><span class="line">也可以是0-&gt;1-&gt;9-&gt;5-&gt;4。</span><br></pre></td></tr></table></figure>

<p>总之， 满 足左部分都是小于3的节点， 中间部分都是等于3的节点（本例中这个部<br>分为空） ， 右部分都是大于3的节点即可。 对某部分内部的节点顺序不做要求。</p>
<p>进阶： 在原问题的要求之上再增加如下两个要求。<br>在左、 中、 右三个部分的内部也做顺序要求， 要求每部分里的节点从左 到右的<br>顺序与原链表中节点的先后次序一致。 例如： 链表9-&gt;0-&gt;4-&gt;5-&gt;1， pivot=3。<br>调整后的链表是0-&gt;1-&gt;9-&gt;4-&gt;5。 在满足原问题要求的同时， 左部分节点从左到<br>右为0、 1。 在原链表中也 是先出现0， 后出现1； 中间部分在本例中为空， 不再<br>讨论； 右部分节点 从左到右为9、 4、 5。 在原链表中也是先出现9， 然后出现4，<br>最后出现5。<br>如果链表长度为N， 时间复杂度请达到O(N)， 额外空间复杂度请达到O(1)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ListNode <span class="title">listPartition2</span><span class="params">(ListNode head, <span class="keyword">int</span> pivot)</span> </span>&#123;</span><br><span class="line">    ListNode sH = <span class="keyword">null</span>; <span class="comment">// small head                            </span></span><br><span class="line">    ListNode sT = <span class="keyword">null</span>; <span class="comment">// small tail                            </span></span><br><span class="line">    ListNode eH = <span class="keyword">null</span>; <span class="comment">// equal head                            </span></span><br><span class="line">    ListNode eT = <span class="keyword">null</span>; <span class="comment">// equal tail                            </span></span><br><span class="line">    ListNode bH = <span class="keyword">null</span>; <span class="comment">// big head                              </span></span><br><span class="line">    ListNode bT = <span class="keyword">null</span>; <span class="comment">// big tail                              </span></span><br><span class="line">    ListNode next; <span class="comment">// save next node                             </span></span><br><span class="line">                                                                 </span><br><span class="line">    <span class="keyword">while</span> (head != <span class="keyword">null</span>) &#123;                                       </span><br><span class="line">        next = head.next;                                        </span><br><span class="line">        <span class="comment">//释放                                                     </span></span><br><span class="line">        head.next = <span class="keyword">null</span>;                                        </span><br><span class="line">        <span class="keyword">if</span> (head.val &lt; pivot) &#123;                                  </span><br><span class="line">            <span class="keyword">if</span> (sH == <span class="keyword">null</span>) &#123;                                    </span><br><span class="line">                sH = head;                                       </span><br><span class="line">                sT = head;                                       </span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;                                             </span><br><span class="line">                sT.next = head;                                  </span><br><span class="line">                sT = head;                                       </span><br><span class="line">            &#125;                                                    </span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (head.val &gt; pivot) &#123;                           </span><br><span class="line">            <span class="keyword">if</span> (eH == <span class="keyword">null</span>) &#123;                                    </span><br><span class="line">                eH = head;                                       </span><br><span class="line">                eT = head;                                       </span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;                                             </span><br><span class="line">                eT.next = head;                                  </span><br><span class="line">                eT = head;                                       </span><br><span class="line">            &#125;                                                    </span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;                                                 </span><br><span class="line">            <span class="keyword">if</span> (bH == <span class="keyword">null</span>) &#123;                                    </span><br><span class="line">                bH = head;                                       </span><br><span class="line">                bT = head;                                       </span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;                                             </span><br><span class="line">                bT.next = head;                                  </span><br><span class="line">                bT = head;                                       </span><br><span class="line">            &#125;                                                    </span><br><span class="line">        &#125;                                                        </span><br><span class="line">        head = next;                                             </span><br><span class="line">    &#125;                                                            </span><br><span class="line">    <span class="comment">// small and equal reconnect                                 </span></span><br><span class="line">    <span class="keyword">if</span> (sT != <span class="keyword">null</span>) &#123;                                            </span><br><span class="line">        sT.next = eH;                                            </span><br><span class="line">        eT = eT == <span class="keyword">null</span> ? sT : eT;                               </span><br><span class="line">    &#125;                                                            </span><br><span class="line">    <span class="comment">// all reconnect                                             </span></span><br><span class="line">    <span class="keyword">if</span> (eT != <span class="keyword">null</span>) &#123;                                            </span><br><span class="line">        eT.next = bH;                                            </span><br><span class="line">    &#125;                                                            </span><br><span class="line">    <span class="keyword">return</span> sH != <span class="keyword">null</span> ? sH : eH != <span class="keyword">null</span> ? eH : bH;               </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="复制含有随机指针节点的链表"><a href="#复制含有随机指针节点的链表" class="headerlink" title="复制含有随机指针节点的链表"></a>复制含有随机指针节点的链表</h2><p>一种特殊的链表节点类描述如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123; </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> value; </span><br><span class="line">    <span class="keyword">public</span> Node next; </span><br><span class="line">    <span class="keyword">public</span> Node rand;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123; </span><br><span class="line">        <span class="keyword">this</span>.value = data; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Node类中的value是节点值,next指针和正常单链表中next指针的意义一样，都指向下一个节点，rand指针是Node类中新增的指针,这个指针可能指向链表中的任意一个节点， 也可能指向null。</p>
<p>给定一个由Node节点类型组成的无环单链表的头节点head，请实现一个函数完成这个链表中所有结构的复制， 并返回复制的新链表的头节点。 </p>
<p>进阶：不使用额外的数据结构，只用有限几个变量， 且在时间复杂度为O(N)内完成原问题要实现的函数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.list.m;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CopyListWithRandom</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> value;</span><br><span class="line">        <span class="keyword">public</span> Node next;</span><br><span class="line">        <span class="keyword">public</span> Node rand;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.value = data;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将节点拷贝到map中，利用map获取源节点的next、rand指针。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> head 头节点</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Node <span class="title">copyListWithRand1</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">        HashMap&lt;Node, Node&gt; map = <span class="keyword">new</span> HashMap&lt;Node, Node&gt;();</span><br><span class="line">        Node cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            map.put(cur, <span class="keyword">new</span> Node(cur.value));</span><br><span class="line">            cur = cur.next;</span><br><span class="line">        &#125;</span><br><span class="line">        cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            map.get(cur).next = map.get(cur.next);</span><br><span class="line">            map.get(cur).rand = map.get(cur.rand);</span><br><span class="line">            cur = cur.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> map.get(head);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 节点的下一个为其next，让后将所有的拷贝节点提取出来</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> head 头指针</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Node <span class="title">copyListWithRand2</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Node cur = head;</span><br><span class="line">        <span class="comment">// copy next</span></span><br><span class="line">        Node next;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            next = cur.next;</span><br><span class="line">            cur.next = <span class="keyword">new</span> Node(cur.value);</span><br><span class="line">            cur.next.next = next;</span><br><span class="line">            cur = next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// copy rand</span></span><br><span class="line">        cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            next = cur.next.next;</span><br><span class="line">            cur.next.rand = cur.rand == <span class="keyword">null</span> ? <span class="keyword">null</span> : cur.rand.next;</span><br><span class="line">            cur = next;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// split</span></span><br><span class="line">        Node res = head.next;</span><br><span class="line">        Node curCopy;</span><br><span class="line">        cur = head;</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            next = cur.next.next;</span><br><span class="line">            curCopy = cur.next;</span><br><span class="line"></span><br><span class="line">            cur.next = next;</span><br><span class="line">            curCopy.next = next != <span class="keyword">null</span> ? next.next : <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">            cur = next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printRandLinkedList</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">        Node cur = head;</span><br><span class="line">        System.out.print(<span class="string">"order: "</span>);</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.print(cur.value + <span class="string">" "</span>);</span><br><span class="line">            cur = cur.next;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">        cur = head;</span><br><span class="line">        System.out.print(<span class="string">"rand:  "</span>);</span><br><span class="line">        <span class="keyword">while</span> (cur != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.print(cur.rand == <span class="keyword">null</span> ? <span class="string">"- "</span> : cur.rand.value + <span class="string">" "</span>);</span><br><span class="line">            cur = cur.next;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Node head = <span class="keyword">null</span>;</span><br><span class="line">        Node res1 = <span class="keyword">null</span>;</span><br><span class="line">        Node res2 = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        head = <span class="keyword">new</span> Node(<span class="number">1</span>);</span><br><span class="line">        head.next = <span class="keyword">new</span> Node(<span class="number">2</span>);</span><br><span class="line">        head.next.next = <span class="keyword">new</span> Node(<span class="number">3</span>);</span><br><span class="line">        head.next.next.next = <span class="keyword">new</span> Node(<span class="number">4</span>);</span><br><span class="line">        head.next.next.next.next = <span class="keyword">new</span> Node(<span class="number">5</span>);</span><br><span class="line">        head.next.next.next.next.next = <span class="keyword">new</span> Node(<span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">        head.rand = head.next.next.next.next.next; <span class="comment">// 1 -&gt; 6</span></span><br><span class="line">        head.next.rand = head.next.next.next.next.next; <span class="comment">// 2 -&gt; 6</span></span><br><span class="line">        head.next.next.rand = head.next.next.next.next; <span class="comment">// 3 -&gt; 5</span></span><br><span class="line">        head.next.next.next.rand = head.next.next; <span class="comment">// 4 -&gt; 3</span></span><br><span class="line">        head.next.next.next.next.rand = <span class="keyword">null</span>; <span class="comment">// 5 -&gt; null</span></span><br><span class="line">        head.next.next.next.next.next.rand = head.next.next.next; <span class="comment">// 6 -&gt; 4</span></span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"head"</span>);</span><br><span class="line">        printRandLinkedList(head);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"Rand1"</span>);</span><br><span class="line">        res1 = copyListWithRand1(head);</span><br><span class="line">        printRandLinkedList(res1);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"Rand2"</span>);</span><br><span class="line">        res2 = copyListWithRand2(head);</span><br><span class="line">        printRandLinkedList(res2);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"head"</span>);</span><br><span class="line">        printRandLinkedList(head);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="两个单链表相交的一系列问题"><a href="#两个单链表相交的一系列问题" class="headerlink" title="两个单链表相交的一系列问题"></a>两个单链表相交的一系列问题</h2><p>单链表可能有环，也可能无环。给定两个单链表的头节点 head1和head2，这两个链表可能相交，也可能不相交。</p>
<p>请实现一个函数， </p>
<ul>
<li>如果两个链表相交， 请返回相交的第一个节点；</li>
<li>如果不相交， 返回null 即可。 </li>
</ul>
<p>要求： 如果链表1 的长度为N， 链表2的长度为M， 时间复杂度请达到 O(N+M)， 额外空间复杂度请达到O(1)</p>
<h3 id="可能情况"><a href="#可能情况" class="headerlink" title="可能情况"></a>可能情况</h3><p><img src="https://s2.ax1x.com/2020/02/11/1oDNut.png" alt="1oDNut.png"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.list.m;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.jelly.algorithm.list.ListNode;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 寻找两个链表交点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FindFirstIntersectNode</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ListNode <span class="title">getIntersectNode</span><span class="params">(ListNode head1, ListNode head2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head1 == <span class="keyword">null</span> || head2 == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ListNode loop1 = getLoopNode(head1);</span><br><span class="line">        ListNode loop2 = getLoopNode(head2);</span><br><span class="line">        <span class="comment">//both no loop</span></span><br><span class="line">        <span class="keyword">if</span> (loop1 == <span class="keyword">null</span> &amp;&amp; loop2 == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> noLoop(head1, head2);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//both has loop</span></span><br><span class="line">        <span class="keyword">if</span> (loop1 != <span class="keyword">null</span> &amp;&amp; loop2 != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> bothLoop(head1, loop1, head2, loop2);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//one has loop the other has no loop. don't intersect.</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Get the entry node of the ring</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ListNode <span class="title">getLoopNode</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head == <span class="keyword">null</span> || head.next == <span class="keyword">null</span> || head.next.next == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ListNode n1 = head.next; <span class="comment">// n1 -&gt; slow</span></span><br><span class="line">        ListNode n2 = head.next.next; <span class="comment">// n2 -&gt; fast</span></span><br><span class="line">        <span class="keyword">while</span> (n1 != n2) &#123;</span><br><span class="line">            <span class="keyword">if</span> (n2.next == <span class="keyword">null</span> || n2.next.next == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            n2 = n2.next.next;</span><br><span class="line">            n1 = n1.next;</span><br><span class="line">        &#125;</span><br><span class="line">        n2 = head; <span class="comment">// n2 -&gt; walk again from head</span></span><br><span class="line">        <span class="keyword">while</span> (n1 != n2) &#123;</span><br><span class="line">            n1 = n1.next;</span><br><span class="line">            n2 = n2.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> n1;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * two no loop list</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ListNode <span class="title">noLoop</span><span class="params">(ListNode head1, ListNode head2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head1 == <span class="keyword">null</span> || head2 == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ListNode cur1 = head1;</span><br><span class="line">        ListNode cur2 = head2;</span><br><span class="line">        <span class="keyword">int</span> n = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> (cur1.next != <span class="keyword">null</span>) &#123;</span><br><span class="line">            n++;</span><br><span class="line">            cur1 = cur1.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (cur2.next != <span class="keyword">null</span>) &#123;</span><br><span class="line">            n--;</span><br><span class="line">            cur2 = cur2.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// end different</span></span><br><span class="line">        <span class="keyword">if</span> (cur1 != cur2) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// cur1 is longer. </span></span><br><span class="line">        cur1 = n &gt; <span class="number">0</span> ? head1 : head2;</span><br><span class="line">        cur2 = cur1 == head1 ? head2 : head1;</span><br><span class="line">        n = Math.abs(n);</span><br><span class="line">        <span class="keyword">while</span> (n != <span class="number">0</span>) &#123;</span><br><span class="line">            n--;</span><br><span class="line">            cur1 = cur1.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (cur1 != cur2) &#123;</span><br><span class="line">            cur1 = cur1.next;</span><br><span class="line">            cur2 = cur2.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> cur1;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * both has loop</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ListNode <span class="title">bothLoop</span><span class="params">(ListNode head1, ListNode loop1, ListNode head2, ListNode loop2)</span> </span>&#123;</span><br><span class="line">        ListNode cur1 = <span class="keyword">null</span>;</span><br><span class="line">        ListNode cur2 = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">// 入口节点相同</span></span><br><span class="line">        <span class="keyword">if</span> (loop1 == loop2) &#123;</span><br><span class="line">            cur1 = head1;</span><br><span class="line">            cur2 = head2;</span><br><span class="line">            <span class="keyword">int</span> n = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">while</span> (cur1 != loop1) &#123;</span><br><span class="line">                n++;</span><br><span class="line">                cur1 = cur1.next;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (cur2 != loop2) &#123;</span><br><span class="line">                n--;</span><br><span class="line">                cur2 = cur2.next;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// cur1 is longer</span></span><br><span class="line">            cur1 = n &gt; <span class="number">0</span> ? head1 : head2;</span><br><span class="line">            cur2 = cur1 == head1 ? head2 : head1;</span><br><span class="line">            n = Math.abs(n);</span><br><span class="line">            <span class="keyword">while</span> (n != <span class="number">0</span>) &#123;</span><br><span class="line">                n--;</span><br><span class="line">                cur1 = cur1.next;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (cur1 != cur2) &#123;</span><br><span class="line">                cur1 = cur1.next;</span><br><span class="line">                cur2 = cur2.next;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> cur1;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//入口节点不同</span></span><br><span class="line">            cur1 = loop1.next;</span><br><span class="line">            <span class="keyword">while</span> (cur1 != loop1) &#123;</span><br><span class="line">                <span class="keyword">if</span> (cur1 == loop2) &#123;</span><br><span class="line">                    <span class="keyword">return</span> loop1;</span><br><span class="line">                &#125;</span><br><span class="line">                cur1 = cur1.next;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;null</span></span><br><span class="line">        ListNode head1 = <span class="keyword">new</span> ListNode(<span class="number">1</span>);</span><br><span class="line">        head1.next = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        head1.next.next = <span class="keyword">new</span> ListNode(<span class="number">3</span>);</span><br><span class="line">        head1.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">4</span>);</span><br><span class="line">        head1.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">5</span>);</span><br><span class="line">        head1.next.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">6</span>);</span><br><span class="line">        head1.next.next.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">7</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 0-&gt;9-&gt;8-&gt;6-&gt;7-&gt;null</span></span><br><span class="line">        ListNode head2 = <span class="keyword">new</span> ListNode(<span class="number">0</span>);</span><br><span class="line">        head2.next = <span class="keyword">new</span> ListNode(<span class="number">9</span>);</span><br><span class="line">        head2.next.next = <span class="keyword">new</span> ListNode(<span class="number">8</span>);</span><br><span class="line">        head2.next.next.next = head1.next.next.next.next.next; <span class="comment">// 8-&gt;6</span></span><br><span class="line">        System.out.println(getIntersectNode(head1, head2).val);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;4...</span></span><br><span class="line">        head1 = <span class="keyword">new</span> ListNode(<span class="number">1</span>);</span><br><span class="line">        head1.next = <span class="keyword">new</span> ListNode(<span class="number">2</span>);</span><br><span class="line">        head1.next.next = <span class="keyword">new</span> ListNode(<span class="number">3</span>);</span><br><span class="line">        head1.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">4</span>);</span><br><span class="line">        head1.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">5</span>);</span><br><span class="line">        head1.next.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">6</span>);</span><br><span class="line">        head1.next.next.next.next.next.next = <span class="keyword">new</span> ListNode(<span class="number">7</span>);</span><br><span class="line">        head1.next.next.next.next.next.next = head1.next.next.next; <span class="comment">// 7-&gt;4</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 0-&gt;9-&gt;8-&gt;2...</span></span><br><span class="line">        head2 = <span class="keyword">new</span> ListNode(<span class="number">0</span>);</span><br><span class="line">        head2.next = <span class="keyword">new</span> ListNode(<span class="number">9</span>);</span><br><span class="line">        head2.next.next = <span class="keyword">new</span> ListNode(<span class="number">8</span>);</span><br><span class="line">        head2.next.next.next = head1.next; <span class="comment">// 8-&gt;2</span></span><br><span class="line">        System.out.println(getIntersectNode(head1, head2).val);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 0-&gt;9-&gt;8-&gt;6-&gt;4-&gt;5-&gt;6..</span></span><br><span class="line">        head2 = <span class="keyword">new</span> ListNode(<span class="number">0</span>);</span><br><span class="line">        head2.next = <span class="keyword">new</span> ListNode(<span class="number">9</span>);</span><br><span class="line">        head2.next.next = <span class="keyword">new</span> ListNode(<span class="number">8</span>);</span><br><span class="line">        head2.next.next.next = head1.next.next.next.next.next; <span class="comment">// 8-&gt;6</span></span><br><span class="line">        System.out.println(getIntersectNode(head1, head2).val);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="二叉树"><a href="#二叉树" class="headerlink" title="二叉树"></a>二叉树</h1><h2 id="在二叉树中找到一个节点的后继节点"><a href="#在二叉树中找到一个节点的后继节点" class="headerlink" title="在二叉树中找到一个节点的后继节点"></a>在二叉树中找到一个节点的后继节点</h2><p>现在有一种新的二叉树节点类型如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123; </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> value; </span><br><span class="line">    <span class="keyword">public</span> Node left;</span><br><span class="line">    <span class="keyword">public</span> Node right; </span><br><span class="line">    <span class="keyword">public</span> Node parent;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123; </span><br><span class="line">        <span class="keyword">this</span>.value = data; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该结构比普通二叉树节点结构多了一个指向父节点的parent指针。</p>
<p>假设有一棵Node类型的节点组成的二叉树， 树中每个节点的parent指针都正确地指向 自己的父节点， 头节点的parent指向null。 只给一个在二叉树中的某个节点 node， 请实现返回node的后继节点的函数。 在二<br>叉树的中序遍历的序列中，node的下一个节点叫作node的后继节点.</p>
<p>中序遍历 左、根、右</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Node <span class="title">getSuccessorNode</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//右节点不为空时，下一个节点为右节点的最左节点</span></span><br><span class="line">	<span class="keyword">if</span> (node.right != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> getLeftMost(node.right);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="comment">//右节点为空，当前是左子节点，返回其父节点，否则找到祖父节点返回</span></span><br><span class="line">		Node parent = node.parent;</span><br><span class="line">		<span class="keyword">while</span> (parent != <span class="keyword">null</span> &amp;&amp; parent.left != node) &#123;</span><br><span class="line">			node = parent;</span><br><span class="line">			parent = node.parent;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> parent;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Node <span class="title">getLeftMost</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (node.left != <span class="keyword">null</span>) &#123;</span><br><span class="line">		node = node.left;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="判断一棵二叉树是否是平衡二叉树"><a href="#判断一棵二叉树是否是平衡二叉树" class="headerlink" title="判断一棵二叉树是否是平衡二叉树"></a>判断一棵二叉树是否是平衡二叉树</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 检验是否是平衡树</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isBalanced</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> process(root) != -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">process</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> left = process(root.left);</span><br><span class="line">    <span class="keyword">if</span> (left == -<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> right = process(root.right);</span><br><span class="line">    <span class="keyword">if</span> (right == -<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> Math.abs(left - right) &gt; <span class="number">1</span> ? -<span class="number">1</span> : Math.max(left, right) + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="判断一棵树是否是搜索二叉树、"><a href="#判断一棵树是否是搜索二叉树、" class="headerlink" title="判断一棵树是否是搜索二叉树、"></a>判断一棵树是否是搜索二叉树、</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 校验是否是平衡二叉搜索树.中序遍历，递增</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isValidBST</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; res = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    middleOrder(root, res);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; res.size(); i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (res.get(i - <span class="number">1</span>) &gt; res.get(i)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">middleOrder</span><span class="params">(TreeNode root, List&lt;Integer&gt; res)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    middleOrder(root.left, res);</span><br><span class="line">    res.add(root.val);</span><br><span class="line">    middleOrder(root.right, res);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="判断一棵树是否是完全二叉树"><a href="#判断一棵树是否是完全二叉树" class="headerlink" title="判断一棵树是否是完全二叉树"></a>判断一棵树是否是完全二叉树</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isCBT</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (head == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	Queue&lt;Node&gt; queue = <span class="keyword">new</span> LinkedList&lt;Node&gt;();</span><br><span class="line">	<span class="keyword">boolean</span> leaf = <span class="keyword">false</span>;</span><br><span class="line">	Node l = <span class="keyword">null</span>;</span><br><span class="line">	Node r = <span class="keyword">null</span>;</span><br><span class="line">	queue.offer(head);</span><br><span class="line">	<span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">		head = queue.poll();</span><br><span class="line">		l = head.left;</span><br><span class="line">		r = head.right;</span><br><span class="line">		<span class="comment">// leaf为true后，左右节点均为空</span></span><br><span class="line">		<span class="comment">// 左节点为空，右节点必须为空</span></span><br><span class="line">		<span class="keyword">if</span> ((leaf &amp;&amp; (l != <span class="keyword">null</span> || r != <span class="keyword">null</span>)) || (l == <span class="keyword">null</span> &amp;&amp; r != <span class="keyword">null</span>)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	    <span class="keyword">if</span> (l != <span class="keyword">null</span>) &#123;</span><br><span class="line">			queue.offer(l);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 右节点为空，leaf标记为true</span></span><br><span class="line">		<span class="keyword">if</span> (r != <span class="keyword">null</span>) &#123;</span><br><span class="line">			queue.offer(r);</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			leaf = <span class="keyword">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="已知一棵完全二叉树，-求其节点的个数"><a href="#已知一棵完全二叉树，-求其节点的个数" class="headerlink" title="已知一棵完全二叉树， 求其节点的个数"></a>已知一棵完全二叉树， 求其节点的个数</h2><p>要求： 时间复杂度低于O(N)， N为这棵树的节点个数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">nodeNum</span><span class="params">(Node head)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (head == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> bs(head, <span class="number">1</span>, mostLeftLevel(head, <span class="number">1</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">bs</span><span class="params">(Node node, <span class="keyword">int</span> l, <span class="keyword">int</span> h)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// leval 和 height相同时，返回1</span></span><br><span class="line">	<span class="keyword">if</span> (l == h) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 右子树高度和完全二叉树高度相等，说明，左树为满树</span></span><br><span class="line">	<span class="comment">// 2^(h-l) 个 + 右子树节点个数</span></span><br><span class="line">	<span class="keyword">if</span> (mostLeftLevel(node.right, l + <span class="number">1</span>) == h) &#123;</span><br><span class="line">		<span class="keyword">return</span> (<span class="number">1</span> &lt;&lt; (h - l)) + bs(node.right, l + <span class="number">1</span>, h);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	    <span class="comment">// 右树层数小1，+ 加上左子树节点个数 </span></span><br><span class="line">		<span class="keyword">return</span> (<span class="number">1</span> &lt;&lt; (h - l - <span class="number">1</span>)) + bs(node.left, l + <span class="number">1</span>, h);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">mostLeftLevel</span><span class="params">(Node node, <span class="keyword">int</span> level)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">while</span> (node != <span class="keyword">null</span>) &#123;</span><br><span class="line">		level++;</span><br><span class="line">		node = node.left;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> level - <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="折纸问题"><a href="#折纸问题" class="headerlink" title="折纸问题"></a>折纸问题</h2><p>请把一段纸条竖着放在桌子上， 然后从纸条的下边向<br>上方对折1次， 压出折痕后展开。 此时 折痕是凹下去的， 即折痕<br>突起的方向指向纸条的背面。 如果从纸条的下边向上方连续对折<br>2 次， 压出折痕后展开， 此时有三条折痕， 从上到下依次是下折<br>痕、 下折痕和上折痕。<br>给定一 个输入参数N， 代表纸条都从下边向上方连续对折N次，<br>请从上到下打印所有折痕的方向。 例如： N=1时， 打印： down<br>N=2时， 打印： down down up</p>
<p>类似二叉树：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">右、中、左的遍历顺序。</span><br><span class="line">            下</span><br><span class="line">        上      下</span><br><span class="line">      上  下  上  下</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printAllFolds</span><span class="params">(<span class="keyword">int</span> N)</span> </span>&#123;</span><br><span class="line">	printProcess(<span class="number">1</span>, N, <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printProcess</span><span class="params">(<span class="keyword">int</span> i, <span class="keyword">int</span> N, <span class="keyword">boolean</span> down)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (i &gt; N) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	printProcess(i + <span class="number">1</span>, N, <span class="keyword">true</span>);</span><br><span class="line">	System.out.println(down ? <span class="string">"down "</span> : <span class="string">"up "</span>);</span><br><span class="line">	printProcess(i + <span class="number">1</span>, N, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="布隆过滤器"><a href="#布隆过滤器" class="headerlink" title="布隆过滤器"></a>布隆过滤器</h1><ul>
<li>bit数组大小：m= - n * ln(p) / (ln2)^2</li>
<li>n: 样本量</li>
<li>p: 0.0001 预期失误率</li>
<li>哈希函数个数：k = ln2 * m / n = 0.7 * m/n</li>
<li>真实失误率：（1-e^(-n*k/m) )^k</li>
</ul>
<h2 id="URL筛选"><a href="#URL筛选" class="headerlink" title="URL筛选"></a>URL筛选</h2><p>不安全网页的黑名单包含100亿个黑名单网页，每个网页的URL最多占用64B，现在要实现一个网页过滤系统，根据网页的URL判断该网页是否在黑名单上。</p>
<h3 id="要求-7"><a href="#要求-7" class="headerlink" title="要求"></a>要求</h3><ol>
<li>允许一定的判断失误率</li>
<li>空间内存限制在30GB以内</li>
</ol>
<p>如果是直接用哈希函数处理，肯定会长处空间限制，所以这里要用到的是布隆过滤器。</p>
<p>布隆过滤器实际上是一个位图bitMap，我们现在假设有一个<strong>长度为m的bit类型的数组</strong>，以及 <strong>k 个互相独立的优秀的哈希函数</strong>，且这<strong>k个哈希函数的输出域都大于或等于m</strong>。</p>
<p>我们将网页的URL作为k个哈希函数的输入对象进行哈希处理，分别得到 k 个值，<strong>这k个值中可能有相同的，但是值之间互相独立不关联的</strong>。我们将这k个值<strong>对m模运算</strong>，得到的 k 个值都在 0~m之间。最后将这 k 个值对应的bitMap的值<strong>置为1</strong>，当我们将所有的URL都处理完毕后，bitMap上的很多位都被置为了1。</p>
<p>当我们要查询一个URL是否在黑名单内时，我们<strong>先将这个URL进行哈希处理</strong> ，因为有K个函数所以得到 k 个值。接着<strong>检查这 k 个值对应的bitMap 位是否为1，如果有一个不为 1，那么说明这个URL不在这个这里面，是安全的网站</strong>，如果对应的 bitMap 位的值都是 1 那么说明这个URL可能在这里面。说明可能是因为当URL的数量很多时，可能会出现不同URL哈希处理后得到相同的值，所以说是<strong>有可能在这里面</strong>。</p>
<hr>
<h1 id="一致性哈希"><a href="#一致性哈希" class="headerlink" title="一致性哈希"></a>一致性哈希</h1><p>所有机器经过hash后，按照顺序排序。分担所有hash的数据。</p>
<p>新机器加入：新机器按照其hash分布到所有的hash环上，该点到下一点的数据拷贝到新机器上即可。</p>
<p>旧机器删除：删除该机器，该点管控数据，拷贝给他相邻节点。</p>
<h2 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h2><p>机器必须达到一定数量，否则数据可能分布严重不均。</p>
<h2 id="解决办法"><a href="#解决办法" class="headerlink" title="解决办法"></a>解决办法</h2><p>每个物理机增加一定数量的虚拟节点，均分整个hash环，根据虚拟节点的数量将数据划分给特定的宿主机存储。</p>
<hr>
<h1 id="岛问题"><a href="#岛问题" class="headerlink" title="岛问题"></a>岛问题</h1><p>一个矩阵中只有0和1两种值，每个位置都可以和自己的上、下、左、右 四个位置相连，如果有一片1连在一起，这个部分叫做一个岛，求一个 矩阵中有多少个岛？<br>举例：<br>0 0 1 0 1 0 1 1 1 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0<br>这个矩阵中有三个岛</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">countIslands</span><span class="params">(<span class="keyword">int</span>[][] m)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (m == <span class="keyword">null</span> || m[<span class="number">0</span>] == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> N = m.length;</span><br><span class="line">	<span class="keyword">int</span> M = m[<span class="number">0</span>].length;</span><br><span class="line">	<span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; N; i++) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; M; j++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (m[i][j] == <span class="number">1</span>) &#123;</span><br><span class="line">				res++;</span><br><span class="line">				infect(m, i, j, N, M);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">infect</span><span class="params">(<span class="keyword">int</span>[][] m, <span class="keyword">int</span> i, <span class="keyword">int</span> j, <span class="keyword">int</span> N, <span class="keyword">int</span> M)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (i &lt; <span class="number">0</span> || i &gt;= N || j &lt; <span class="number">0</span> || j &gt;= M || m[i][j] != <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	m[i][j] = <span class="number">2</span>;</span><br><span class="line">	infect(m, i + <span class="number">1</span>, j, N, M);</span><br><span class="line">	infect(m, i - <span class="number">1</span>, j, N, M);</span><br><span class="line">	infect(m, i, j + <span class="number">1</span>, N, M);</span><br><span class="line">	infect(m, i, j - <span class="number">1</span>, N, M);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[][] m1 = &#123;  &#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, </span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span> &#125;, </span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span> &#125;,</span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, </span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, </span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span> &#125;,</span><br><span class="line">			        &#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, &#125;;</span><br><span class="line">	System.out.println(countIslands(m1));</span><br><span class="line"></span><br><span class="line">	<span class="keyword">int</span>[][] m2 = &#123;  &#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, </span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span> &#125;, </span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span> &#125;,</span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span> &#125;, </span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, </span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span> &#125;,</span><br><span class="line">					&#123; <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span> &#125;, &#125;;</span><br><span class="line">	System.out.println(countIslands(m2));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="并查集"><a href="#并查集" class="headerlink" title="并查集"></a>并查集</h1><p>一种结构，主要提供两种功能</p>
<ul>
<li>两个集合是否属于一个集合</li>
<li>合并两个集合</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">UnionFindSet</span> </span>&#123;</span><br><span class="line">	<span class="comment">// k：当前节点，v：父节点</span></span><br><span class="line">	<span class="keyword">public</span> HashMap&lt;Node, Node&gt; fatherMap;</span><br><span class="line">	<span class="comment">// k：当前节点，v：当前节点所代表的集合中有多少其他节点</span></span><br><span class="line">	<span class="keyword">public</span> HashMap&lt;Node, Integer&gt; sizeMap;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 构造函数，必须一次给定所有的节点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">UnionFindSet</span><span class="params">(List&lt;Node&gt; nodes)</span> </span>&#123;</span><br><span class="line">		makeSets(nodes);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 初始化所有节点，初始化时所有节点指向自己，size为 1</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">makeSets</span><span class="params">(List&lt;Node&gt; nodes)</span> </span>&#123;</span><br><span class="line">		fatherMap = <span class="keyword">new</span> HashMap&lt;Node, Node&gt;();</span><br><span class="line">		sizeMap = <span class="keyword">new</span> HashMap&lt;Node, Integer&gt;();</span><br><span class="line">		<span class="keyword">for</span> (Node node : nodes) &#123;</span><br><span class="line">			fatherMap.put(node, node);</span><br><span class="line">			sizeMap.put(node, <span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 递归找到node的父节点</span></span><br><span class="line">    <span class="comment">// 然后并将查找路径上的节点，挂在代表节点下</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> Node <span class="title">findHead</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">		Node father = fatherMap.get(node);</span><br><span class="line">		<span class="keyword">if</span> (father != node) &#123;</span><br><span class="line">			father = findHead(father);</span><br><span class="line">		&#125;</span><br><span class="line">		fatherMap.put(node, father);</span><br><span class="line">		<span class="keyword">return</span> father;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 对外提供的方法，两个节点是否属于同一个集合</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSameSet</span><span class="params">(Node a, Node b)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> findHead(a) == findHead(b);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 合并两个集合，参数为两个集合的代表节点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">union</span><span class="params">(Node a, Node b)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (a == <span class="keyword">null</span> || b == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		Node aHead = findHead(a);</span><br><span class="line">		Node bHead = findHead(b);</span><br><span class="line">		<span class="keyword">if</span> (aHead != bHead) &#123;</span><br><span class="line">			<span class="keyword">int</span> aSetSize= sizeMap.get(aHead);</span><br><span class="line">			<span class="keyword">int</span> bSetSize = sizeMap.get(bHead);</span><br><span class="line">			<span class="keyword">if</span> (aSetSize &lt;= bSetSize) &#123;</span><br><span class="line">				fatherMap.put(aHead, bHead);</span><br><span class="line">				sizeMap.put(bHead, aSetSize + bSetSize);</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				fatherMap.put(bHead, aHead);</span><br><span class="line">				sizeMap.put(aHead, aSetSize + bSetSize);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="前缀树"><a href="#前缀树" class="headerlink" title="前缀树"></a>前缀树</h1><p>arr2中有哪些字符，是arr1中出现的？请打印</p>
<p>arr2中有哪些字符，是作为arr1中某个字符串前缀出现的？请 打印</p>
<p>arr2中有哪些字符，是作为arr1中某个字符串前缀出现的？请打印 arr2中出现次数最大的前缀。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">TrieNode</span> </span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">int</span> path;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">int</span> end;</span><br><span class="line">	<span class="keyword">public</span> TrieNode[] nexts;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">TrieNode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		path = <span class="number">0</span>;</span><br><span class="line">		end = <span class="number">0</span>;</span><br><span class="line">		nexts = <span class="keyword">new</span> TrieNode[<span class="number">26</span>];</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Trie</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> TrieNode root;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Trie</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		root = <span class="keyword">new</span> TrieNode();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (word == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">char</span>[] chs = word.toCharArray();</span><br><span class="line">		TrieNode node = root;</span><br><span class="line">		<span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; chs.length; i++) &#123;</span><br><span class="line">			index = chs[i] - <span class="string">'a'</span>;</span><br><span class="line">			<span class="keyword">if</span> (node.nexts[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">				node.nexts[index] = <span class="keyword">new</span> TrieNode();</span><br><span class="line">			&#125;</span><br><span class="line">			node = node.nexts[index];</span><br><span class="line">			node.path++;</span><br><span class="line">		&#125;</span><br><span class="line">		node.end++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (search(word) != <span class="number">0</span>) &#123;</span><br><span class="line">			<span class="keyword">char</span>[] chs = word.toCharArray();</span><br><span class="line">			TrieNode node = root;</span><br><span class="line">			<span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; chs.length; i++) &#123;</span><br><span class="line">				index = chs[i] - <span class="string">'a'</span>;</span><br><span class="line">				<span class="keyword">if</span> (--node.nexts[index].path == <span class="number">0</span>) &#123;</span><br><span class="line">					node.nexts[index] = <span class="keyword">null</span>;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				node = node.nexts[index];</span><br><span class="line">			&#125;</span><br><span class="line">			node.end--;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">search</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (word == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">char</span>[] chs = word.toCharArray();</span><br><span class="line">		TrieNode node = root;</span><br><span class="line">		<span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; chs.length; i++) &#123;</span><br><span class="line">			index = chs[i] - <span class="string">'a'</span>;</span><br><span class="line">			<span class="keyword">if</span> (node.nexts[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			node = node.nexts[index];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> node.end;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">prefixNumber</span><span class="params">(String pre)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (pre == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">char</span>[] chs = pre.toCharArray();</span><br><span class="line">		TrieNode node = root;</span><br><span class="line">		<span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; chs.length; i++) &#123;</span><br><span class="line">			index = chs[i] - <span class="string">'a'</span>;</span><br><span class="line">			<span class="keyword">if</span> (node.nexts[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			node = node.nexts[index];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> node.path;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	Trie trie = <span class="keyword">new</span> Trie();</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuo"</span>));</span><br><span class="line">	trie.insert(<span class="string">"zuo"</span>);</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuo"</span>));</span><br><span class="line">	trie.delete(<span class="string">"zuo"</span>);</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuo"</span>));</span><br><span class="line">	trie.insert(<span class="string">"zuo"</span>);</span><br><span class="line">	trie.insert(<span class="string">"zuo"</span>);</span><br><span class="line">	trie.delete(<span class="string">"zuo"</span>);</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuo"</span>));</span><br><span class="line">	trie.delete(<span class="string">"zuo"</span>);</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuo"</span>));</span><br><span class="line">	trie.insert(<span class="string">"zuoa"</span>);</span><br><span class="line">	trie.insert(<span class="string">"zuoac"</span>);</span><br><span class="line">	trie.insert(<span class="string">"zuoab"</span>);</span><br><span class="line">	trie.insert(<span class="string">"zuoad"</span>);</span><br><span class="line">	trie.delete(<span class="string">"zuoa"</span>);</span><br><span class="line">	System.out.println(trie.search(<span class="string">"zuoa"</span>));</span><br><span class="line">	System.out.println(trie.prefixNumber(<span class="string">"zuo"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="贪心算法"><a href="#贪心算法" class="headerlink" title="贪心算法"></a>贪心算法</h1><h2 id="切金条"><a href="#切金条" class="headerlink" title="切金条"></a>切金条</h2><p>一块金条切成两半，是需要花费和长度数值一样的铜板的。比如 长度为20的 金条，不管切成长度多大的两半，都要花费20个铜 板。一群人想整分整块金 条，怎么分最省铜板？ 例如,给定数组{10,20,30}，代表一共三个人，整块金条长度为 10+20+30=60. 金条要分成10,20,30三个部分。 如果， 先把长 度60的金条分成10和50，花费60 再把长度50的金条分成20和30， 花费50 一共花费110铜板。 但是如果， 先把长度60的金条分成30和30，花费60 再把长度30 金条分成10和20，花费30 一共花费90铜板。 输入一个数组，返回分割的最小代价。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">lessMoney</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		PriorityQueue&lt;Integer&gt; pQ = <span class="keyword">new</span> PriorityQueue&lt;&gt;();</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">			pQ.add(arr[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">int</span> cur = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">while</span> (pQ.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">			cur = pQ.poll() + pQ.poll();</span><br><span class="line">			sum += cur;</span><br><span class="line">			pQ.add(cur);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> sum;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<h2 id="做项目-IPO"><a href="#做项目-IPO" class="headerlink" title="做项目(IPO)"></a>做项目(IPO)</h2><p>输入： </p>
<ul>
<li>参数1，正数数组costs </li>
<li>参数2，正数数组profits </li>
<li>参数3， 正数k </li>
<li>参数4，正数m </li>
</ul>
<p>costs[i]表示i号项目的花费 profits[i]表示i号项目在扣除花 费之后还能挣到的钱(利润) k表示你不能并行、只能串行的最多 做k个项目 m表示你初始的资金 说明：你每做完一个项目，马上获得的收益，可以支持你去做下 一个 项目。 输出： 你最后获得的最大钱数。</p>
<p>构建两个堆：</p>
<p>按照花费构建小根堆，当花费小于当前所有资金时，进入按照收益构建的大根堆，每次大根堆中给的第一个。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">int</span> p;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">int</span> c;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> p, <span class="keyword">int</span> c)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.p = p;</span><br><span class="line">			<span class="keyword">this</span>.c = c;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MinCostComparator</span> <span class="keyword">implements</span> <span class="title">Comparator</span>&lt;<span class="title">Node</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Node o1, Node o2)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> o1.c - o2.c;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MaxProfitComparator</span> <span class="keyword">implements</span> <span class="title">Comparator</span>&lt;<span class="title">Node</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Node o1, Node o2)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> o2.p - o1.p;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">findMaximizedCapital</span><span class="params">(<span class="keyword">int</span> k, <span class="keyword">int</span> W, <span class="keyword">int</span>[] Profits, <span class="keyword">int</span>[] Capital)</span> </span>&#123;</span><br><span class="line">		Node[] nodes = <span class="keyword">new</span> Node[Profits.length];</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; Profits.length; i++) &#123;</span><br><span class="line">			nodes[i] = <span class="keyword">new</span> Node(Profits[i], Capital[i]);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		PriorityQueue&lt;Node&gt; minCostQ = <span class="keyword">new</span> PriorityQueue&lt;&gt;(<span class="keyword">new</span> MinCostComparator());</span><br><span class="line">		PriorityQueue&lt;Node&gt; maxProfitQ = <span class="keyword">new</span> PriorityQueue&lt;&gt;(<span class="keyword">new</span> MaxProfitComparator());</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; nodes.length; i++) &#123;</span><br><span class="line">			minCostQ.add(nodes[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; k; i++) &#123;</span><br><span class="line">			<span class="keyword">while</span> (!minCostQ.isEmpty() &amp;&amp; minCostQ.peek().c &lt;= W) &#123;</span><br><span class="line">				maxProfitQ.add(minCostQ.poll());</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (maxProfitQ.isEmpty()) &#123;</span><br><span class="line">				<span class="keyword">return</span> W;</span><br><span class="line">			&#125;</span><br><span class="line">			W += maxProfitQ.poll().p;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> W;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<h2 id="一个数据流中，随时可以取得中位数"><a href="#一个数据流中，随时可以取得中位数" class="headerlink" title="一个数据流中，随时可以取得中位数"></a>一个数据流中，随时可以取得中位数</h2><h2 id="最低字典序"><a href="#最低字典序" class="headerlink" title="最低字典序"></a>最低字典序</h2><p>给定一个字符串类型的数组strs，找到一种拼接方式，使得把所有字符串拼起来之后形成的字符串具有最低的字典序。</p>
<p>注意：</p>
<p>不能直接按照字典序比较，如 ba、b 直接按照字典序比较 ba &gt; b 拼接字符串 bba，但是bab更小。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MyComparator</span> <span class="keyword">implements</span> <span class="title">Comparator</span>&lt;<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(String a, String b)</span> </span>&#123;</span><br><span class="line">	    <span class="comment">// 直接按照字典序比较是错误的</span></span><br><span class="line">		<span class="keyword">return</span> (a + b).compareTo(b + a);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">lowestString</span><span class="params">(String[] strs)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (strs == <span class="keyword">null</span> || strs.length == <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	Arrays.sort(strs, <span class="keyword">new</span> MyComparator());</span><br><span class="line">	String res = <span class="string">""</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; strs.length; i++) &#123;</span><br><span class="line">		res += strs[i];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	String[] strs1 = &#123; <span class="string">"jibw"</span>, <span class="string">"ji"</span>, <span class="string">"jp"</span>, <span class="string">"bw"</span>, <span class="string">"jibw"</span> &#125;;</span><br><span class="line">	System.out.println(lowestString(strs1));</span><br><span class="line"></span><br><span class="line">	String[] strs2 = &#123; <span class="string">"ba"</span>, <span class="string">"b"</span> &#125;;</span><br><span class="line">	System.out.println(lowestString(strs2));</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="宣讲会"><a href="#宣讲会" class="headerlink" title="宣讲会"></a>宣讲会</h2><p>一些项目要占用一个会议室宣讲，会议室不能同时容纳两个项目 的宣讲。 给你每一个项目开始的时间和结束的时间(给你一个数 组，里面 是一个个具体的项目)，你来安排宣讲的日程，要求会 议室进行 的宣讲的场次最多。返回这个最多的宣讲场次。</p>
<p>按照结束时间排序</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Program</span> </span>&#123;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">int</span> start;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">int</span> end;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">Program</span><span class="params">(<span class="keyword">int</span> start, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.start = start;</span><br><span class="line">			<span class="keyword">this</span>.end = end;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ProgramComparator</span> <span class="keyword">implements</span> <span class="title">Comparator</span>&lt;<span class="title">Program</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Program o1, Program o2)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> o1.end - o2.end;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">bestArrange</span><span class="params">(Program[] programs, <span class="keyword">int</span> start)</span> </span>&#123;</span><br><span class="line">		Arrays.sort(programs, <span class="keyword">new</span> ProgramComparator());</span><br><span class="line">		<span class="keyword">int</span> result = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; programs.length; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (start &lt;= programs[i].start) &#123;</span><br><span class="line">				result++;</span><br><span class="line">				start = programs[i].end;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>–</p>
<h1 id="递归-amp-动态规划"><a href="#递归-amp-动态规划" class="headerlink" title="递归&amp;动态规划"></a>递归&amp;动态规划</h1><p>暴力递归： </p>
<ol>
<li>把问题转化为规模缩小了的同类问题的子问题</li>
<li>有明确的不需要继续进行递归的条件(base case)</li>
<li>有当得到了子问题的结果之后的决策过程</li>
<li>不记录每一个 子问题的解</li>
</ol>
<p>动态规划 </p>
<ol>
<li>从暴力递归中来</li>
<li>将每一个子问题的解记录下来，避免重复计算</li>
<li>把暴力递归的过程，抽象成了状态表达</li>
<li>并且存在化简状态表达，使其更加简洁的可能</li>
</ol>
<h2 id="求n-的结果"><a href="#求n-的结果" class="headerlink" title="求n!的结果"></a>求n!的结果</h2><p>n的阶乘依赖于 n-1 的阶乘， n-1 的阶乘依赖于 n-2 的阶乘……依赖 1 的阶乘。</p>
<p>于是，反过来，可以从 1 的阶乘计算到 n的阶乘</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">long</span> <span class="title">getFactorial1</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1L</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> (<span class="keyword">long</span>) n * getFactorial1(n - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">long</span> <span class="title">getFactorial2</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">long</span> result = <span class="number">1L</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">		result *= i;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> n = <span class="number">5</span>;</span><br><span class="line">    System.out.println(getFactorial1(n));</span><br><span class="line">	System.out.println(getFactorial2(n));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="汉诺塔问题"><a href="#汉诺塔问题" class="headerlink" title="汉诺塔问题"></a>汉诺塔问题</h2><p>三个柱子。from、to、help </p>
<p>抽象问题：</p>
<ol>
<li>将from 上的 n 个盘子中的 n-1 个移动到 help上</li>
<li>将from 剩余的第 n 个盘子移动到to上</li>
<li>将help 上的n-1 个盘子移动到to上</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">hanoi</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &gt; <span class="number">0</span>) &#123;</span><br><span class="line">		func(n, n, <span class="string">"left"</span>, <span class="string">"mid"</span>, <span class="string">"right"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">func</span><span class="params">(<span class="keyword">int</span> rest, <span class="keyword">int</span> down, String from, String help, String to)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (rest == <span class="number">1</span>) &#123;</span><br><span class="line">		System.out.println(<span class="string">"move "</span> + down + <span class="string">" from "</span> + from + <span class="string">" to "</span> + to);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		func(rest - <span class="number">1</span>, down - <span class="number">1</span>, from, to, help);</span><br><span class="line">		func(<span class="number">1</span>, down, from, help, to);</span><br><span class="line">		func(rest - <span class="number">1</span>, down - <span class="number">1</span>, help, from, to);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="打印全部子序列"><a href="#打印全部子序列" class="headerlink" title="打印全部子序列"></a>打印全部子序列</h2><p>打印一个字符串的全部子序列，包括空字符串</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printAllSubsquence</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(str == <span class="keyword">null</span>|| <span class="string">""</span>.equal(str))&#123;</span><br><span class="line">	    <span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	process(str.toCharArray(), <span class="number">0</span> ,<span class="string">""</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(<span class="keyword">char</span>[] str, <span class="keyword">int</span> i, String res)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(i == str.length)&#123;</span><br><span class="line">        System.out.println(res);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 决策：不加当前字符</span></span><br><span class="line">    process(str, i+<span class="number">1</span>, res);</span><br><span class="line">    <span class="comment">// 决策：加当前字符</span></span><br><span class="line">    process(str, i+<span class="number">1</span>, res+String.valueOf(str[i]));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="打印全排列"><a href="#打印全排列" class="headerlink" title="打印全排列"></a>打印全排列</h2><p>打印一个字符串的全部排列</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.string;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 字符串的全排列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AllPermutations</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printAllPermutations</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (str == <span class="keyword">null</span> || <span class="string">""</span>.equals(str)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        process(str.toCharArray(), <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(<span class="keyword">char</span>[] chs, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (i == chs.length) &#123;</span><br><span class="line">            System.out.println(String.valueOf(chs));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = i; j &lt; chs.length; j++) &#123;</span><br><span class="line">            process(deepCopyAndSwap(chs, i, j), i + <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">char</span>[] deepCopyAndSwap(<span class="keyword">char</span>[] chs, <span class="keyword">int</span> i, <span class="keyword">int</span> j) &#123;</span><br><span class="line">        <span class="keyword">char</span>[] res = Arrays.copyOf(chs, chs.length);</span><br><span class="line">        <span class="keyword">char</span> tmp = res[i];</span><br><span class="line">        res[i] = res[j];</span><br><span class="line">        res[j] = tmp;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        printAllPermutations(<span class="string">"abc"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="生牛问题"><a href="#生牛问题" class="headerlink" title="生牛问题"></a>生牛问题</h2><p>母牛每年生一只母牛，新出生的母牛成长三年后也能每年生一只母牛，假设不会死。求N年后，母牛的数量。</p>
<p>因为题中牛不会死，三年后可以生母牛。那么可以得到递推公式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f(n) = f(n-1) + f(n-3)</span><br><span class="line">今年牛数量  = 去年牛数量 + 三年前牛数量(它们将会生小牛)</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">cowNumber1</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &lt; <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span> || n == <span class="number">2</span> || n == <span class="number">3</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> n;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> cowNumber1(n - <span class="number">1</span>) + cowNumber1(n - <span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">cowNumber2</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &lt; <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span> || n == <span class="number">2</span> || n == <span class="number">3</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> n;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> res = <span class="number">3</span>;</span><br><span class="line">	<span class="keyword">int</span> pre = <span class="number">2</span>;</span><br><span class="line">	<span class="keyword">int</span> prepre = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">int</span> tmp1 = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">int</span> tmp2 = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">4</span>; i &lt;= n; i++) &#123;</span><br><span class="line">		tmp1 = res;</span><br><span class="line">		tmp2 = pre;</span><br><span class="line">		</span><br><span class="line">		res = res + prepre;</span><br><span class="line">		</span><br><span class="line">		pre = tmp1;</span><br><span class="line">		prepre = tmp2;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> n = <span class="number">20</span>;</span><br><span class="line">	System.out.println(cowNumber1(n));</span><br><span class="line">	System.out.println(cowNumber2(n));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="生牛问题-母牛只能活10年"><a href="#生牛问题-母牛只能活10年" class="headerlink" title="生牛问题(母牛只能活10年)"></a>生牛问题(母牛只能活10年)</h2><p>如果每只母牛只能活10年（先生后死），求N年后，母牛的数量。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f(n) = f(n-1) + f(n-3) - (f(n-10) - f(n-11))</span><br><span class="line">今年牛数量  = 去年牛数量 + 三年前牛数量(它们将会生小牛) - 十年前出生的小牛(如果是第十年没生小牛就死亡，应减2倍 十年前出生小牛的量)</span><br></pre></td></tr></table></figure>

<h2 id="递归逆序栈"><a href="#递归逆序栈" class="headerlink" title="递归逆序栈"></a>递归逆序栈</h2><p>给你一个栈，请你逆序这个栈，不能申请额外的数据结构，只能 使用递归函数。如何实现？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jelly.algorithm.stack;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Stack;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 递归查找栈底元素弹出，然后入栈</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ReverseStackUsingRecursive</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">reverse</span><span class="params">(Stack&lt;Integer&gt; stack)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (stack == <span class="keyword">null</span> || stack.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> last = getAndRemoveLast(stack);</span><br><span class="line">        reverse(stack);</span><br><span class="line">        stack.push(last);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getAndRemoveLast</span><span class="params">(Stack&lt;Integer&gt; stack)</span> </span>&#123;</span><br><span class="line">        Integer pop = stack.pop();</span><br><span class="line">        <span class="keyword">if</span> (stack.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">return</span> pop;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 弹出的pop不是栈底元素，递归查找，并将pop重新入栈</span></span><br><span class="line">            <span class="keyword">int</span> last = getAndRemoveLast(stack);</span><br><span class="line">            stack.push(pop);</span><br><span class="line">            <span class="keyword">return</span> last;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Stack&lt;Integer&gt; stack = initStack();</span><br><span class="line">        reverse(stack);</span><br><span class="line">        printStack(stack);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 测试 初始化栈</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Stack&lt;Integer&gt; <span class="title">initStack</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">        stack.push(<span class="number">1</span>);</span><br><span class="line">        stack.push(<span class="number">2</span>);</span><br><span class="line">        stack.push(<span class="number">3</span>);</span><br><span class="line">        stack.push(<span class="number">4</span>);</span><br><span class="line">        <span class="keyword">return</span> stack;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 测试 打印栈</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printStack</span><span class="params">(Stack&lt;Integer&gt; stack)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">            System.out.print(stack.pop() + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="最小路径"><a href="#最小路径" class="headerlink" title="最小路径"></a>最小路径</h2><h3 id="无后效性问题都可以改成动态规划"><a href="#无后效性问题都可以改成动态规划" class="headerlink" title="无后效性问题都可以改成动态规划"></a>无后效性问题都可以改成动态规划</h3><blockquote>
<p>无后效性，当前选择对后边选择决策无关。当前可变参数确定，最后返回值是确定的。</p>
</blockquote>
<p>给你一个二维数组，二维数组中的每个数都是正数，要求从左上角走到右下角，每一步只能向右或者向下。沿途经过的数字要累加起来。返回最小的路径和</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">minPath1</span><span class="params">(<span class="keyword">int</span>[][] matrix)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> process1(matrix, matrix.length - <span class="number">1</span>, matrix[<span class="number">0</span>].length - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 递归版</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">process1</span><span class="params">(<span class="keyword">int</span>[][] matrix, <span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> res = matrix[i][j];</span><br><span class="line">	<span class="keyword">if</span> (i == <span class="number">0</span> &amp;&amp; j == <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> res;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (i == <span class="number">0</span> &amp;&amp; j != <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> res + process1(matrix, i, j - <span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (i != <span class="number">0</span> &amp;&amp; j == <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> res + process1(matrix, i - <span class="number">1</span>, j);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res + Math.min(process1(matrix, i, j - <span class="number">1</span>), process1(matrix, i - <span class="number">1</span>, j));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 动态规划版</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">minPath2</span><span class="params">(<span class="keyword">int</span>[][] m)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (m == <span class="keyword">null</span> || m.length == <span class="number">0</span> || m[<span class="number">0</span>] == <span class="keyword">null</span> || m[<span class="number">0</span>].length == <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> row = m.length;</span><br><span class="line">	<span class="keyword">int</span> col = m[<span class="number">0</span>].length;</span><br><span class="line">	<span class="keyword">int</span>[][] dp = <span class="keyword">new</span> <span class="keyword">int</span>[row][col];</span><br><span class="line">	dp[<span class="number">0</span>][<span class="number">0</span>] = m[<span class="number">0</span>][<span class="number">0</span>];</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; row; i++) &#123;</span><br><span class="line">		dp[i][<span class="number">0</span>] = dp[i - <span class="number">1</span>][<span class="number">0</span>] + m[i][<span class="number">0</span>];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt; col; j++) &#123;</span><br><span class="line">		dp[<span class="number">0</span>][j] = dp[<span class="number">0</span>][j - <span class="number">1</span>] + m[<span class="number">0</span>][j];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; row; i++) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt; col; j++) &#123;</span><br><span class="line">			dp[i][j] = Math.min(dp[i - <span class="number">1</span>][j], dp[i][j - <span class="number">1</span>]) + m[i][j];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dp[row - <span class="number">1</span>][col - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line">	</span><br><span class="line"><span class="comment">// for test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span>[][] generateRandomMatrix(<span class="keyword">int</span> rowSize, <span class="keyword">int</span> colSize) &#123;</span><br><span class="line">	<span class="keyword">if</span> (rowSize &lt; <span class="number">0</span> || colSize &lt; <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span>[][] result = <span class="keyword">new</span> <span class="keyword">int</span>[rowSize][colSize];</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i != result.length; i++) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j != result[<span class="number">0</span>].length; j++) &#123;</span><br><span class="line">			result[i][j] = (<span class="keyword">int</span>) (Math.random() * <span class="number">10</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[][] m = &#123; &#123; <span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">9</span> &#125;, &#123; <span class="number">8</span>, <span class="number">1</span>, <span class="number">3</span>, <span class="number">4</span> &#125;, &#123; <span class="number">5</span>, <span class="number">0</span>, <span class="number">6</span>, <span class="number">1</span> &#125;, &#123; <span class="number">8</span>, <span class="number">8</span>, <span class="number">4</span>, <span class="number">0</span> &#125; &#125;;</span><br><span class="line">	System.out.println(minPath1(m));</span><br><span class="line">	System.out.println(minPath2(m));</span><br><span class="line"></span><br><span class="line">	m = generateRandomMatrix(<span class="number">6</span>, <span class="number">7</span>);</span><br><span class="line">	System.out.println(minPath1(m));</span><br><span class="line">	System.out.println(minPath2(m));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="背包问题"><a href="#背包问题" class="headerlink" title="背包问题"></a>背包问题</h2><p>给你一个数组arr，和一个整数aim。如果可以任意选择arr中的数字，能不能累加得到aim，返回true或者false</p>
<h3 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h3><p>每个位置 i 有 要和不要 两种选择；叶节点会看自己这里的结果是不是 aim，从而向父结点返回 true 或 false，父结点比较子节点的结果，有一个为 true 就一直返回 true，否则返回 false。</p>
<p><img src="https://s2.ax1x.com/2020/02/16/39kjYj.png" alt="39kjYj.png"></p>
<p>如上图所示：数组 arr = {3, 2, 5} ，aim = 7：</p>
<p>f(0, 0)：代表0位置处状态值为0的点；</p>
<p>f(2, 5)：代表2位置处状态值为5的点。</p>
<p>只要有叶节点的值等于 aim 的值，则会返回 true。</p>
<p>动态规划版图解：<br><img src="https://s2.ax1x.com/2020/02/16/39kgeO.png" alt="39kgeO.png"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">money1</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> process(arr, <span class="number">0</span>, <span class="number">0</span>, aim);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">process</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> i, <span class="keyword">int</span> sum, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (sum == aim) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// sum != aim</span></span><br><span class="line">	<span class="keyword">if</span> (i == arr.length) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> process(arr, i + <span class="number">1</span>, sum, aim) || process(arr, i + <span class="number">1</span>, sum + arr[i], aim);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 动态规划版</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">money2</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">boolean</span>[][] dp = <span class="keyword">new</span> <span class="keyword">boolean</span>[arr.length + <span class="number">1</span>][aim + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; dp.length; i++) &#123;</span><br><span class="line">		dp[i][aim] = <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = arr.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> j = aim - <span class="number">1</span>; j &gt;= <span class="number">0</span>; j--) &#123;</span><br><span class="line">			dp[i][j] = dp[i + <span class="number">1</span>][j];</span><br><span class="line">			<span class="keyword">if</span> (j + arr[i] &lt;= aim) &#123;</span><br><span class="line">				dp[i][j] = dp[i][j] || dp[i + <span class="number">1</span>][j + arr[i]];</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dp[<span class="number">0</span>][<span class="number">0</span>];</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[] arr = &#123; <span class="number">1</span>, <span class="number">4</span>, <span class="number">8</span> &#125;;</span><br><span class="line">	<span class="keyword">int</span> aim = <span class="number">12</span>;</span><br><span class="line">	System.out.println(money1(arr, aim));</span><br><span class="line">	System.out.println(money2(arr, aim));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="商品价值"><a href="#商品价值" class="headerlink" title="商品价值"></a>商品价值</h2><p>给定两个数组w和v，两个数组长度相等，w[i]表示第i件商品的 重量，v[i]表示第i件商品的价值。 再给定一个整数bag，要求 你挑选商品的重量加起来一定不能超 过bag，返回满足这个条件 下，你能获得的最大价值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">maxValue1</span><span class="params">(<span class="keyword">int</span>[] c, <span class="keyword">int</span>[] p, <span class="keyword">int</span> bag)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> process1(c, p, <span class="number">0</span>, <span class="number">0</span>, bag);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">process1</span><span class="params">(<span class="keyword">int</span>[] weights, <span class="keyword">int</span>[] values, <span class="keyword">int</span> i, <span class="keyword">int</span> alreadyweight, <span class="keyword">int</span> bag)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (alreadyweight &gt; bag) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (i == weights.length) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> Math.max(</span><br><span class="line">			process1(weights, values, i + <span class="number">1</span>, alreadyweight, bag),</span><br><span class="line">			</span><br><span class="line">			values[i] + process1(weights, values, i + <span class="number">1</span>, alreadyweight + weights[i], bag)</span><br><span class="line">			);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">maxValue2</span><span class="params">(<span class="keyword">int</span>[] c, <span class="keyword">int</span>[] p, <span class="keyword">int</span> bag)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[][] dp = <span class="keyword">new</span> <span class="keyword">int</span>[c.length + <span class="number">1</span>][bag + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = c.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> j = bag; j &gt;= <span class="number">0</span>; j--) &#123;</span><br><span class="line">			dp[i][j] = dp[i + <span class="number">1</span>][j];</span><br><span class="line">			<span class="keyword">if</span> (j + c[i] &lt;= bag) &#123;</span><br><span class="line">				dp[i][j] = Math.max(dp[i][j], p[i] + dp[i + <span class="number">1</span>][j + c[i]]);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dp[<span class="number">0</span>][<span class="number">0</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span>[] c = &#123; <span class="number">3</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">7</span> &#125;;</span><br><span class="line">	<span class="keyword">int</span>[] p = &#123; <span class="number">5</span>, <span class="number">6</span>, <span class="number">3</span>, <span class="number">19</span> &#125;;</span><br><span class="line">	<span class="keyword">int</span> bag = <span class="number">11</span>;</span><br><span class="line">	System.out.println(maxValue1(c, p, bag));</span><br><span class="line">	System.out.println(maxValue2(c, p, bag));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束 <i class="fa fa-paw"></i> 感谢您的阅读-------------</div>
    
</div>

      
    </div>
    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/alg-frequenceCode/">高频算法题-zs</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Big Jelly 的个人博客">Big Jelly</a></p>
  <p><span>发布时间:</span>2018年10月18日 - 10:53</p>
  <p><span>最后更新:</span>2020年03月07日 - 11:47</p>
  <p><span>原始链接:</span><a href="/alg-frequenceCode/" title="高频算法题-zs">https://jelly54.github.io/alg-frequenceCode/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://jelly54.github.io/alg-frequenceCode/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
    </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Big Jelly 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Big Jelly 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag"><i class="fa fa-tag"></i> 算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/alg-masterForm/" rel="next" title="master公式&归并排序">
                <i class="fa fa-chevron-left"></i> master公式&归并排序
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/mybatis-plusStart/" rel="prev" title="mybatis-plus入坑指南">
                mybatis-plus入坑指南 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
	<div id="gitalk-container"></div>

  

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 展示广告 -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="4663393885" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Big Jelly">
            
              <p class="site-author-name" itemprop="name">Big Jelly</p>
              <p class="site-description motion-element" itemprop="description">Nothing is easier than to deceive oneself</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">68</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://github.com/jelly54" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="mailto:jelly_54@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                外链小站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode.com/" title="LeetCode" rel="external nofollow" target="_blank">LeetCode</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.dooccn.com/" title="在线编辑代码" rel="external nofollow" target="_blank">在线编辑代码</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.chuangzaoshi.com/code" title="创造狮导航" rel="external nofollow" target="_blank">创造狮导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://24mail.chacuo.net/?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq" title="24Mail" rel="external nofollow" target="_blank">24Mail</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://e.xitu.io/" title="掘金酱" rel="external nofollow" target="_blank">掘金酱</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#排序问题"><span class="nav-number">1.</span> <span class="nav-text">排序问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#小和问题"><span class="nav-number">1.1.</span> <span class="nav-text">小和问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#逆序对问题"><span class="nav-number">1.2.</span> <span class="nav-text">逆序对问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#相邻两数的最大差值"><span class="nav-number">1.3.</span> <span class="nav-text">相邻两数的最大差值</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#栈和队列"><span class="nav-number">2.</span> <span class="nav-text">栈和队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#数组实现固定大小的队列和栈"><span class="nav-number">2.1.</span> <span class="nav-text">数组实现固定大小的队列和栈</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现返回栈中最小元素"><span class="nav-number">2.2.</span> <span class="nav-text">实现返回栈中最小元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求"><span class="nav-number">2.2.1.</span> <span class="nav-text">要求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何仅用队列结构实现栈结构？"><span class="nav-number">2.3.</span> <span class="nav-text">如何仅用队列结构实现栈结构？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何仅用栈结构实现队列结构？"><span class="nav-number">2.4.</span> <span class="nav-text">如何仅用栈结构实现队列结构？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#猫狗队列"><span class="nav-number">2.5.</span> <span class="nav-text">猫狗队列</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-1"><span class="nav-number">2.5.1.</span> <span class="nav-text">要求</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#矩阵"><span class="nav-number">3.</span> <span class="nav-text">矩阵</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#转圈打印矩阵"><span class="nav-number">3.1.</span> <span class="nav-text">转圈打印矩阵</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-2"><span class="nav-number">3.1.1.</span> <span class="nav-text">要求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#旋转正方形矩阵"><span class="nav-number">3.2.</span> <span class="nav-text">旋转正方形矩阵</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-3"><span class="nav-number">3.2.1.</span> <span class="nav-text">要求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#反转单向和双向链表"><span class="nav-number">3.3.</span> <span class="nav-text">反转单向和双向链表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-4"><span class="nav-number">3.3.1.</span> <span class="nav-text">要求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#“之”-字形打印矩阵"><span class="nav-number">3.4.</span> <span class="nav-text">“之” 字形打印矩阵</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-5"><span class="nav-number">3.4.1.</span> <span class="nav-text">要求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#在行列都排好序的矩阵中找数"><span class="nav-number">3.5.</span> <span class="nav-text">在行列都排好序的矩阵中找数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-6"><span class="nav-number">3.5.1.</span> <span class="nav-text">要求</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#链表"><span class="nav-number">4.</span> <span class="nav-text">链表</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#打印两个有序链表的公共节点"><span class="nav-number">4.1.</span> <span class="nav-text">打印两个有序链表的公共节点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#判断一个链表是否为回文结构"><span class="nav-number">4.2.</span> <span class="nav-text">判断一个链表是否为回文结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#将单向链表按某值划分成左边小、-中间相等、-右边大的形式"><span class="nav-number">4.3.</span> <span class="nav-text">将单向链表按某值划分成左边小、 中间相等、 右边大的形式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复制含有随机指针节点的链表"><span class="nav-number">4.4.</span> <span class="nav-text">复制含有随机指针节点的链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#两个单链表相交的一系列问题"><span class="nav-number">4.5.</span> <span class="nav-text">两个单链表相交的一系列问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#可能情况"><span class="nav-number">4.5.1.</span> <span class="nav-text">可能情况</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二叉树"><span class="nav-number">5.</span> <span class="nav-text">二叉树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#在二叉树中找到一个节点的后继节点"><span class="nav-number">5.1.</span> <span class="nav-text">在二叉树中找到一个节点的后继节点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#判断一棵二叉树是否是平衡二叉树"><span class="nav-number">5.2.</span> <span class="nav-text">判断一棵二叉树是否是平衡二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#判断一棵树是否是搜索二叉树、"><span class="nav-number">5.3.</span> <span class="nav-text">判断一棵树是否是搜索二叉树、</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#判断一棵树是否是完全二叉树"><span class="nav-number">5.4.</span> <span class="nav-text">判断一棵树是否是完全二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#已知一棵完全二叉树，-求其节点的个数"><span class="nav-number">5.5.</span> <span class="nav-text">已知一棵完全二叉树， 求其节点的个数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#折纸问题"><span class="nav-number">5.6.</span> <span class="nav-text">折纸问题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#布隆过滤器"><span class="nav-number">6.</span> <span class="nav-text">布隆过滤器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#URL筛选"><span class="nav-number">6.1.</span> <span class="nav-text">URL筛选</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#要求-7"><span class="nav-number">6.1.1.</span> <span class="nav-text">要求</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一致性哈希"><span class="nav-number">7.</span> <span class="nav-text">一致性哈希</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#问题"><span class="nav-number">7.1.</span> <span class="nav-text">问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解决办法"><span class="nav-number">7.2.</span> <span class="nav-text">解决办法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#岛问题"><span class="nav-number">8.</span> <span class="nav-text">岛问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#并查集"><span class="nav-number">9.</span> <span class="nav-text">并查集</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前缀树"><span class="nav-number">10.</span> <span class="nav-text">前缀树</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#贪心算法"><span class="nav-number">11.</span> <span class="nav-text">贪心算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#切金条"><span class="nav-number">11.1.</span> <span class="nav-text">切金条</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#做项目-IPO"><span class="nav-number">11.2.</span> <span class="nav-text">做项目(IPO)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一个数据流中，随时可以取得中位数"><span class="nav-number">11.3.</span> <span class="nav-text">一个数据流中，随时可以取得中位数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最低字典序"><span class="nav-number">11.4.</span> <span class="nav-text">最低字典序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#宣讲会"><span class="nav-number">11.5.</span> <span class="nav-text">宣讲会</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#递归-amp-动态规划"><span class="nav-number">12.</span> <span class="nav-text">递归&amp;动态规划</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#求n-的结果"><span class="nav-number">12.1.</span> <span class="nav-text">求n!的结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#汉诺塔问题"><span class="nav-number">12.2.</span> <span class="nav-text">汉诺塔问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#打印全部子序列"><span class="nav-number">12.3.</span> <span class="nav-text">打印全部子序列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#打印全排列"><span class="nav-number">12.4.</span> <span class="nav-text">打印全排列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生牛问题"><span class="nav-number">12.5.</span> <span class="nav-text">生牛问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生牛问题-母牛只能活10年"><span class="nav-number">12.6.</span> <span class="nav-text">生牛问题(母牛只能活10年)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#递归逆序栈"><span class="nav-number">12.7.</span> <span class="nav-text">递归逆序栈</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最小路径"><span class="nav-number">12.8.</span> <span class="nav-text">最小路径</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#无后效性问题都可以改成动态规划"><span class="nav-number">12.8.1.</span> <span class="nav-text">无后效性问题都可以改成动态规划</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#背包问题"><span class="nav-number">12.9.</span> <span class="nav-text">背包问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#分析"><span class="nav-number">12.9.1.</span> <span class="nav-text">分析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#商品价值"><span class="nav-number">12.10.</span> <span class="nav-text">商品价值</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

      <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
      <!-- 侧边栏广告 -->
      <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="7563237003" data-ad-format="auto" data-full-width-responsive="true"></ins>
      <script>
      	(adsbygoogle = window.adsbygoogle || []).push({});
      </script>
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright"> &copy; 2017 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Big Jelly</span>

</div>

<div class="powered-by">
	
		<span class="post-meta-item-icon">
			<i class="fa fa-area-chart"></i>
		</span>
		
			<span class="post-meta-item-text">Site words total count&#58;</span>
		
		<span title="Site words total count">140.8k</span>
	
  
	
		<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

		<span class="post-meta-divider">|</span>
		<span class="post-visit-item-icon">
			<i class="fa fa-user-md"></i>
		</span>
		<span class="busuanzi_container_site_uv">
			Visitors to this site: <span id="busuanzi_value_site_uv"></span>
		</span>
	
  


	
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <script src="/js/md5.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: 'ca31692554c3aea431f0',
          clientSecret: '1173c9e9c3c9038304c9a5b08929a359cae9f847',
          repo: 'jelly54.github.io',
          owner: 'jelly54',
          admin: ['jelly54'],
          id: md5(location.pathname),
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  



  
<script type="text/javascript" color="0,0,255" opacity="0.7" zindex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>


<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":true,"model":{"scale":1,"jsonPath":"/live2dw/assets/miku.model.json"},"display":{"position":"right","width":200,"height":400,"hOffset":0,"vOffset":-5},"mobile":{"show":true,"scale":0.5},"react":{"opacity":0.9},"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
